将字典中的列表连接成单个列表
我有一个字典,里面存储了一些键值对:
myDict = dict({'red': [1, 2],
'blue': [3, 4]})
我想把这些键和值合并成一个列表:
['red_1', 'red_2', 'blue_3', 'blue_4']
有什么最有效的方法来做到这一点呢?
2 个回答
2
我故意没有用一行代码来回答,因为你似乎对Python还不太熟悉。
# Method 1 : As you know the length each list(values)
# as you have used curly braces, you dont need to use dict
myDict = {'red': [1, 2],
'blue': [3, 4]}
lst = []
for k, v in myDict.items():
#concatenate key, underscore and value of respective index and append. as value is integer convert to string
ele_1 = f'{k}_{str(v[0])}'
ele_2 = f'{k}_{str(v[1])}'
lst.append(ele_1)
lst.append(ele_2)
print(lst) #Output : ['red_1', 'red_2', 'blue_3', 'blue_4']
# Method 2: If you dont know the length of the values
lst = []
for k, v in myDict.items():
#iterate thru each value
for x in v:
ele = f'{k}_{str(x)}'
lst.append(ele)
print(lst) #Output : ['red_1', 'red_2', 'blue_3', 'blue_4']
4
你只需要用一种叫做 列表推导式
的方法来创建一个新的列表,像这样:
result = [f'{key}_{val}' for key, values in myDict.items() for val in values]
其实还有很多其他的方法可以做到这一点。