我有一个解决这个问题的方法,但我很好奇是否有更好的方法。 我有这样的字典:
dict1 = {
'key1':[['value1','value2','value3'],['value4','value5','value6']],
'key2':[['value7','value8','value9'],['value10','value11','value12']],
'key3':[['value13','value14','value15'],['value16','value17','value18']]}
我想将其转换为嵌套列表,并将密钥插入新的子列表中,如下所示:
nestedlist = [
['value1','value2','key1','value3'],['value4','value5','key1','value6'],
['value7','value8','key1','value9'],['value10','value11','key2','value12'],
['value13','value14','key2','value15'],['value16','value17','key2','value18'],
['value10','value11','key3','value12'],['value13','value14','key3','value15'],
['value16','value17','key3','value18']]
我通过以下方式解决这个问题:
keys = [*dict1]
newlist = []
for item in keys:
for item2 in dict1[item]:
item2.insert(2,item)
newlist.append(item2)
那么,我该如何改进这段代码?
答案 0 :(得分:3)
这是通过列表理解的一种方式:
res = [[w[0], w[1], k, w[2]] for k, v in dict1.items() for w in v]
# [['value1', 'value2', 'key1', 'value3'],
# ['value4', 'value5', 'key1', 'value6'],
# ['value7', 'value8', 'key2', 'value9'],
# ['value10', 'value11', 'key2', 'value12'],
# ['value13', 'value14', 'key3', 'value15'],
# ['value16', 'value17', 'key3', 'value18']]
答案 1 :(得分:1)
我会做得非常相似。这里显示的唯一区别是:
items()
无需在dict1上执行列表解包或[]访问。 {{1}}返回包含每个键和dict值的元组列表。