作为使用Python的初学者,我正在尝试使用if语句使用值填充字典。如果你有关于为什么这不起作用的想法,我将非常感谢你的意见。 Mahalo提前!
#first list
groslist = [0, 1, 2, 3]
#dictionary whose keys are items in grosList
grosdict = {k:[] for k in groslist}
#second list whose items correspond with dictionary's keys
indivlist = [0, 0, 1, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3]
#third list whose nth item ID corresponds indivlist
indivIDlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
#Populate dictionary with indivIDlist values (dict keys correspond with indivlist items)
for ID in indivlist:
for ID in groslist:
x = 0;
if indivlist[x] == groslist[x]:
grosdict[indivlist[x]] = indivIDlist[x];
x += 1
这是我的理想输出:
print CG_IDdict
{0: [0, 1, 3], 1: [2, 4, 5, 6], 2: [7, 8, 9, 10], 3: [11, 12]}
答案 0 :(得分:1)
看看预期的产量,这似乎是你想要做的。
for key, value in zip(indivlist, indivIDlist):
grosdict[key].append(value)
print grosdict
#{0: [0, 1, 3], 1: [2, 4, 5, 6], 2: [7, 8, 9, 10], 3: [11, 12]}
zip功能。将这两个列表的元素组合在一起,如下所示:
[(0, 0), (0, 1), (1, 2), (0, 3), (1, 4), (1, 5), (1, 6), (2, 7), (2, 8), (2, 9), (2, 10), (3, 11), (3, 12)]
然后通过这个列表循环,我们有值和相应的键,将它们插入到字典中。
看看原始代码。那里有一些问题。
此修改后的代码给出了相同的结果。
x = 0
for ID_indiv in indivlist:
for ID_grod in groslist:
if ID_indiv == ID_grod:
grosdict[ID_indiv].append(indivIDlist[x])
x += 1
或者您可以进行小编辑并使用{{3}}:
for x, ID_indiv in enumerate(indivlist):
for ID_grod in groslist:
if ID_indiv == ID_grod:
grosdict[ID_indiv].append(indivIDlist[x])
答案 1 :(得分:0)
import collections
groslist = [0, 1, 2, 3]
grosdict = collections.defaultdict(list) # Uses the standard library’s default dictionary type.
indivlist = [0, 0, 1, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3]
indivIDlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
for key, value in zip(indivlist, indivIDlist):
grosdict[key].append(value)
assert grosdict == {0: [0, 1, 3],
1: [2, 4, 5, 6],
2: [7, 8, 9, 10],
3: [11, 12]}
print(dict(grosdict))
使用像M4rtini这样的内置zip功能可能是最优雅的解决方案。使用标准库的defaultdict
类型,代替字典理解也可能有所帮助。