gpt4 book ai didi

python - 将元组作为字典中的值处理(在列表推导中)

转载 作者:行者123 更新时间:2023-11-28 21:51:35 25 4
gpt4 key购买 nike

我有这样一本字典:

>>> pprint.pprint(d){'a': ('abc', 'pqr', 'xyz'), 'b': ('abc', 'lmn', 'uvw'), 'c': ('efg', 'xxx', 'yyy')}

Now, given a variable x, I want to be able to list all the keys from the dict where the first element in the tuple is equal to x. Hence I do this (on Python 2.6):

>>> [ k for k, v in d if v[0] == x ]

我明白了

Traceback (most recent call last):  File "", line 1, in ValueError: need more than 1 value to unpack

我该如何纠正这个问题?

最佳答案

你快到了,只是忘记了带有字典的 .items():

>>> d = {'a': ('abc', 'pqr', 'xyz'),
... 'b': ('abc', 'lmn', 'uvw'),
... 'c': ('efg', 'xxx', 'yyy')}
>>> x = 'abc'
>>> [ k for k, v in d.items() if v[0] == x ]
['a', 'b']

如果您不想使用 .items,您也可以迭代 key 本身:

>>> [ k for k in d if d[k][0] == x ]
['a', 'b']

关于python - 将元组作为字典中的值处理(在列表推导中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29982809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com