如何在Python中高效地检查字典列表中的值?

问题描述 投票:0回答:1

假设我有一个字典列表:

universe_creatures = [
    {'type': 'dragon', 'weight': 1400},
    {'type': 'kraken', 'weight': 6000},
    {'type': 'elf', 'weight': 75}
]

如何在简短的代码中搜索某个字典值中是否存在某种类型,但又尽可能高效?

我目前拥有的:

typ = 'dragon'
found = False

我相信 for 循环是最有效的,因为它迭代一次,并且没有生成器调用那样的开销。

# for loop

for c in universe_creatures:
    if typ == c['type']:
        found = True
        break

但我正在寻找一个较短的短语,如下面的两个,并且想了解生成器表达式与上面的 for 循环相比是否太昂贵。 我认为生成器比列表理解更有效,因为后者多次迭代数据。

# generator expression

found = typ in (c['type'] for c in universe_creatures)
# list comprehension
# one iteration to create new list, then 'in' operator iterates again to search.

found = typ in [c['type'] for c in universe_creatures]
python list for-loop search generator
1个回答
0
投票
found = 1 if any([x['type'] == 'dragon' for x in universe_creatures]) else 0
print(found) # Output: 1

如果您想要相反的条件,请相应地更改 0 和 1。请注意,1 和 0 可以分别替换

True
False
。虽然打印输出只是 0 或 1,但您可以在后续步骤的任何条件语句中使用它,就像使用
True
False
一样。例如,您可以在后面的步骤中使用,如
if found:

© www.soinside.com 2019 - 2024. All rights reserved.