如何在 python 中使用列表推导来避免 indexError

How can I avoid indexError using list comprehension in python

提问人:oj43085 提问时间:9/15/2023 更新时间:9/16/2023 访问量:34

问:

我有一个字典数组,我想检查字典数组中是否有特定键并检索该项目。 我知道如何使用列表推导来做到这一点,但是有没有办法在不这样做的情况下避免indexError?

result = [x[fruit]["weight"] for x in [{"apple":{"weight":0.25}},{"orange":{"weight":0.25}}] if fruit in x.keys()]
if result:
   weight_of_fruit = result[0]

我宁愿这样做:

result = [x[fruit]["weight"] for x in [{"apple":{"weight":0.25}},{"orange":{"weight":0.25}}] if fruit in x.keys()][0]

但这有 indexError 的风险。

我可以用类似于 dict .get() 方法的数组做些什么吗?所以我可以用一行干净的代码来写这个。

python-3.x 列表 列表推导式

评论

0赞 Alexander 9/15/2023
如果列表为空,结果的价值是多少?

答:

0赞 Daviid 9/15/2023 #1

我仍然认为它很丑陋且不可读,但如果你真的必须,请使用

fruit = 'unknown'
result = [x[fruit]["weight"] if fruit in x.keys() else None for x in [{"apple":{"weight":0.25}},{"orange":{"weight":0.25}}]][0]

请记住,我已经更改了顺序并添加了if fruit in x.keys()else None

2赞 Andrej Kesely 9/16/2023 #2

您可以使用默认值:next()

lst = [{"apple": {"weight": 0.25}}, {"orange": {"weight": 0.25}}]

fruit = "pear"
result = next((d[fruit]["weight"] for d in lst if fruit in d), [])

print(result)

指纹:

[]
0赞 ankur yadav 9/16/2023 #3

您可以通过使用 conditional 来实现这一点.get()

next():用于循环访问字典列表。

法典:

fruit = "apple"
data = [{"apple": {"weight": 0.25}}, {"orange": {"weight": 0.25}}]

weight_of_fruit = next((x.get(fruit, {}).get("weight", None) for x in data), None)
print(weight_of_fruit)

输出:

0.25

解释:此代码在字典列表中查找指定水果的权重,如果未找到该水果,则返回 。None