在理解中匹配字典键元组项

Matching dictionary key tuple items in a comprehension

当使用扫描字典的理解表达式时, 如果我知道字典的键是简单的 2 项元组, 是否可以将它们 "expand" 命名为变量?

例如如果我有:

d = { ('car','blue') : 24,
      ('car',    'red'  ): 5,
      ('plant',     'green'): 12,
      ('box','blue' ): 3
}

我知道我能做到

[d[key] for key in d.keys() if key[1]=='blue']

并得到

[24, 3]

但这失去了很多语义,我想知道我是否可以以某种方式做更多的事情:

[count for {(object,color):count} in d if color=='blue']

(我知道这是行不通的)。 我也不明白为什么最后一个表达式返回的错误是:

SyntaxError: can't assign to literal

我会选择:

[count for (object, color), count in d.items() if color == 'blue']

作为最清晰的解决方案。

你得到的错误是因为当使用 in 关键字时 python 试图将 d 字典中的项目分配给 {(object,color):count} 这是字面意思创建一个新词典。相反,使用 (object, color), count 因为这是 python 扩展字典项的方式。

你不能完全做到这一点,但如果你 "upgrade" 你的 namedtuples 键,你可以接近。我使用 'kind' 作为 namedtuple 中第一项的名称,因为 object 是一个内置类型,虽然我们可以在这里安全地使用它,但我认为它会使代码有点令人困惑。

from collections import namedtuple

d = { ('car', 'blue') : 24,
      ('car', 'red'): 5,
      ('plant', 'green'): 12,
      ('box', 'blue'): 3
}

Thing = namedtuple('Thing', ('kind', 'color'))
d = {Thing(*key): count for key, count in d.items()}
print(d)

lst = [count for key, count in d.items() if key.color == 'blue']
print(lst)
lst = [count for key, count in d.items() if key.kind == 'car']
print(lst)

输出

{Thing(kind='car', color='blue'): 24, Thing(kind='car', color='red'): 5, Thing(kind='plant', color='green'): 12, Thing(kind='box', color='blue'): 3}
[24, 3]
[24, 5]

实际上,您并不真的需要 命名元组,尽管我认为它们使它更好一些。 ;)

d = { ('car', 'blue') : 24,
      ('car', 'red'): 5,
      ('plant', 'green'): 12,
      ('box', 'blue'): 3
}

lst = [count for (kind, color), count in d.items() if color == 'blue']
print(lst)

有可能。尝试:

  [d.get((object,color)) for object,color in d.keys() if color == 'blue']

这个returns

  [24, 3]