我有一个数字列表和一个包含名称(键)和数字(值)的字典 我需要迭代名为lotto的列表,然后根据字典中的名称值检查它们,如果我得到匹配,则从字典值中删除该数字。
继承人到目前为止我所拥有的只是打印出原始字典键和值
players = {'ray': [1,2,3,6,7,8,], 'al':[1,2,3,4,8,9,]}
lotto =[1,2,3,4,5,6,]
for i in players.values():
if i in lotto:
players.values.remove(i)
print (players)
任何帮助appriciated
答案 0 :(得分:1)
您正以错误的方式访问dict值。看看以下内容:
players = {'ray': [1,2,3,6,7,8,], 'al':[1,2,3,4,8,9,]}
lotto =[1,2,3,4,5,6,]
for p, val in players.items():
for num in lotto:
if num in val:
players[p].remove(num)
print (players) # {'al': [8, 9], 'ray': [7, 8]}
如果列表值中的项目顺序对您不重要,您可以使用以下更快的变体:
players = {'ray': [1,2,3,6,7,8], 'al':[1,2,3,4,8,9]}
lotto = [1,2,3,4,5,6]
lotto = set(lotto)
for p, val in players.items():
players[p] = list(set(val) - lotto)
print (players) # {'ray': [8, 7], 'al': [8, 9]}
也可以在下面的单行中压缩(它重新创建dict
而不是修改它):
players = {k: list(set(val) - lotto) for k, v in players.items()}
答案 1 :(得分:0)
您的问题是您尝试从错误的列表中删除您的号码。 players.values
是每个键值的列表,而不是每个键的个别值。请改用每个密钥的单个值:
players = {'ray': [1,2,3,6,7,8,], 'al':[1,2,3,4,8,9,]}
lotto = [1,2,3,4,5,6,]
for key, value in players.items():
for i in lotto:
if i in value:
value.remove(i)
print(players)
然后可以通过使用词典理解缩短:
players = {'ray': [1,2,3,6,7,8,], 'al':[1,2,3,4,8,9,]}
lotto =[1,2,3,4,5,6,]
players = {k: list(set(v) - set(lotto)) for k, v in players.items()}
print(players) # {'ray': [8, 7], 'al': [8, 9]}
此外,如果您的计划中的列表顺序无关紧要,我建议您改为使用set
。它们提供了有效的元素查找,并使这样的事情变得非常简单:
>>> players = {'ray': {1,2,3,6,7,8,}, 'al':{1,2,3,4,8,9,}}
>>> lotto = {1,2,3,4,5,6,}
>>> {k: v - lotto for k, v in players.items()}
{'ray': {8, 7}, 'al': {8, 9}}
>>>
答案 2 :(得分:0)
你可以这样过滤:
players = {'ray': [1,2,3,6,7,8,], 'al':[1,2,3,4,8,9,]}
lotto =[1,2,3,4,5,6]
new_players = {a:[i for i in b if i not in lotto] for a, b in players.items()}
输出:
{'al': [8, 9], 'ray': [7, 8]}