【问题标题】:How to search for the dictionary keys in a list如何在列表中搜索字典键
【发布时间】:2016-02-22 21:56:16
【问题描述】:

假设我有一本字典:

lst = {'adore': 10, 'hate': 10, 'hello': 10, 'pigeon': 1, 'would': 5, 'elections': 5}

我有一个列表:

mylist = [['a new', 'party'], ['to', 'lol'], ['compete'], ['in', 'adore', 'the 2013'], ['federal', 'elections'], ['The Free', 'Voters'], ['leadership', 'declined to'], ['join forces', 'according to', 'a leaked'], ['email from', 'Bernd Lucke'], ['Advocating', 'adore'] ]

我希望能够在列表中搜索字典中的键。如果列表中的单词是键,则获取该键的值并将其添加到计数器。最后,得到所有值的总和。

有没有办法做到这一点?

【问题讨论】:

  • 你的意思是mylist = ['a', 'new', 'party', 'to', 'compete', 'in', 'the', '2013', 'federal', 'elections.',...]?还是mylist = [['a new', 'party'], ['to', 'lol'],...]
  • 抱歉给大家带来了困惑,为了更有意义,我做了一些修改
  • 啊,感谢编辑:D
  • 现在,请检查我的答案是否正确。

标签: python list loops search dictionary


【解决方案1】:

像这样?

lst = {'adore': 10, 'hate': 10, 'hello': 10, 'pigeon': 1, 'would': 5, 'elections': 5}
mylist = [['a new', 'party'], ['to', 'lol'], ['compete'], ['in', 'adore', 'the 2013'], ['federal', 'elections'], ['The Free', 'Voters'], ['leadership', 'declined to'], ['join forces', 'according to', 'a leaked'], ['email from', 'Bernd Lucke'], ['Advocating', 'adore']]

print([lst.get(i) for j in mylist for i in j if lst.get(i) != None])
print(sum([lst.get(i) for j in mylist for i in j if lst.get(i) != None]))

输出:

[10, 5, 10]
25

如果你不喜欢他们一行:

total = []

for i in mylist:
    for j in i:
        if lst.get(i) != None:
            total.append(lst.get(i))

print(sum(total))

【讨论】:

  • 有没有办法用 if 语句做到这一点?
  • @JohnGringus:已编辑,这是您要找的吗?
【解决方案2】:

也许你可以用更 Pythonic 的方式来做到这一点。

lst = {'adore': 10, 'hate': 10, 'hello': 10, 'pigeon': 1, 'would': 5}
counter = {'adore': 0, 'hate': 0, 'hello': 0, 'pigeon': 0, 'would': 0}
mylist = [['a new', 'party'], ['to', 'lol'], ['compete'], ['in', 'adore', 'the 2013'], ['federal', 'elections'], ['The Free', 'Voters'], ['leadership', 'declined to'], ['join forces', 'according to', 'a leaked'], ['email from', 'Bernd Lucke'], ['Advocating', 'adore'] ]

def func():
    for key in lst.keys():
        for item in mylist:
            if key in item:
                counter[key] = counter[key] + lst[key]

func()
print sum(counter.values())

【讨论】:

  • 每次在列表中找到键时,我如何才能添加分配给键的值,而不仅仅是添加 1?
  • 不是我所说的“pythonic”:-/
  • 已编辑,如果我理解您的需要,您可以使用临时字典来存储出现次数,然后获取该字典的所有值并将它们与总数相加。 @brunodesthuilliers 抱歉,我不是专家。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多