python - 如何在字典上使用 list extend() 和 map 函数

标签 python python-3.x

我是 python 的新手,正在尝试了解 map 函数的工作原理

我有一个输入字典,键是一个字符串,值是一个字符串列表

input_dict = {'Mobile': ['Redmi', 'Samsung', 'Realme'], 
'Laptop': ['Dell', 'HP'],
'TV': ['Videocon', 'Sony'] }

我想把它转换成如下的列表

['Mobile_Redmi', 'Mobile_Samsung', 'Mobile_Realme', 'Laptop_Dell', 'Laptop_HP', 'TV_Videocon', 'TV_Sony']

所以我尝试使用 map 函数和列表扩展方法,如下所示。

def mapStrings(item):
    key, value_list = item[0], item[1]  
    result = []
    for val in value_list:
        result.append(key+"_"+val)
    return result

result_list = []
result_list.extend(map(mapStrings, input_dict.items()))
print(result_list)

上面的代码给了我

[['Mobile_Redmi', 'Mobile_Samsung', 'Mobile_Realme'], ['Laptop_Dell', 'Laptop_HP'], ['TV_Videocon', 'TV_Sony']]

我试图理解为什么 result_list.extend() 没有产生所需的输出。

最佳答案

extend将可迭代对象的所有元素添加到列表中。在这种情况下,元素本身就是列表,因此您会得到一个嵌套列表。你想要的是用字典中的 each 列表单独扩展列表,比如:

result_list = []
for item in input_dict.items():
    result_list.extend(mapStrings(item))

如果你真的想使用map,你可以使用:

result_list = [item for items in map(mapStrings, input_dict.items()) for item in items]

更多方法请看How to make a flat list out of list of lists?请注意,您实际上并不是在处理列表的列表,而是在处理一个 map 对象,因此请注意细微差别。

关于python - 如何在字典上使用 list extend() 和 map 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63435894/

相关文章:

python - 添加到日期的 timedelta 是否考虑闰年?

python - 可以在 pandas 数据框中创建子列吗?

python - 了解机器学习过程和 K Fold 交叉验证

python - 如何预定义Python变量

python - 如何将 Scikit-Learn 的 RandomizedSearchCV 与 Tensorflow 的 ImageDataGenerator 结合使用

python - 操作系统错误: [Errno 13] Permission denied

python-3.x - 如何使用所有列创建频率矩阵

python,可能是马尔可夫链的变体?

python - 尽管 update_idletasks() ,tkinter 光标直到操作后才发生变化

python - 有效测试二维 numpy 数组中是否存在字符串