Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在字典上使用list extend()和map函数_Python_Python 3.x - Fatal编程技术网

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

Python 如何在字典上使用list extend()和map函数,python,python-3.x,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', 'Lapt

我是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()没有产生所需的输出。

将iterable的所有元素添加到列表中。在本例中,元素本身就是列表,因此可以得到嵌套列表。您需要使用dict中的每个列表扩展列表,例如:

result\u list=[]
对于输入目录项()中的项:
结果列表扩展(映射字符串(项))
如果确实要使用
映射
,可以使用:

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

要了解更多方法,请注意,您实际上并不是在处理列表列表,而是处理
map
对象,因此请注意细微差异。

sum(map(mapStrings,input_dict.items()),[])
是一种众所周知的反模式,当您可以在线性时间内平展列表时,它是二次时间。请注意,
sum
函数实际上会抛出一个错误,如果您试图用字符串执行此操作以防止发生这种情况!基本上,您不应该使用序列串联来展平列表。否则这是一个很好的答案!因此,您可以只需执行
[映射中的子列表项(…)子列表项]
或从itertools导入链中执行
,然后执行
列表(链)。从_iterable(映射(…))
我知道这一点,并考虑添加有关它的注释,这就是为什么最终会这样。我的主要建议是常规循环,但也有其他选择,您不必使用sum来处理
map
,基本上可以得到一个平面图operation@juanpa.arrivillaga你是对的,完全同意。换成更一般的注释,您可能希望先从列表理解开始,然后再转到
map
和其他高阶函数。