以下是我的一个python函数的摘录:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
d_list = []
for key,value in d.iteritems():
temp = [key, value]
d_list.append(temp)
当我打印d_list
时,它目前给了我:
>>>print d_list
[['ANIMAL', ['CAT', 'DOG', 'FISH', 'HEDGEHOG']]]
如何重写该功能,以便它给我:
>>>print d_list
[['ANIMAL', 'CAT'],['ANIMAL', 'DOG'],['ANIMAL', 'FISH'],['ANIMAL', 'HEDGEHOG']]
答案 0 :(得分:4)
两个嵌套循环可以轻松完成此任务 -
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
d_list = []
for key, values in d.iteritems():
for value in values:
d_list.append([key, value])
使用列表理解 -
d_list = [[k,v] for k, values in d.iteritems() for v in values]
对于python 3.x,您应该将iteritems
更改为items
答案 1 :(得分:1)
我就是这样做的。我会直接迭代密钥的值。
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
d_list = []
for value in d['ANIMAL']:
temp = ['ANIMAL',value]
d_list.append(temp)
print (d_list)
结果:
[['ANIMAL', 'CAT'], ['ANIMAL', 'DOG'], ['ANIMAL', 'FISH'], ['ANIMAL', 'HEDGEHOG']]
答案 2 :(得分:0)
你需要第二个循环:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
d_list = []
for key, values in d.iteritems():
for value in values:
temp_list=[key, value]
d_list.append(temp)