gpt4 book ai didi

python - 从混合列表中解包元组值

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:07 24 4
gpt4 key购买 nike

假设我有以下列表

lst = [("key1", "2"), ("key3", "4"), "somestring", 12345]

我想从中构建一个 dict(使用 dictcomp,即):

d = {key: value 
for item in lst
for key, value in [item]
if isinstance(item, tuple)}

这将因 ValueError(太多值无法解包)而爆炸。
if 子句何时被评估(当然,这对解包至关重要)?
注意:我知道我之前可以使用 filter/lambda 但想知道是否可以一步完成。

最佳答案

我认为这就是您要找的:

>>> lst = [("key1", "2"), ("key3", "4"), "somestring", 12345]
>>> dict([i for i in lst if type(i) is tuple])
{'key1': '2', 'key3': '4'}

关于python - 从混合列表中解包元组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55245277/

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