Tru*_*ran 1 python dictionary list object
如果我有一个简单的列表对象:
shapes = [
{
'shape': 'square',
'width': 40,
'height': 40
},
{
'shape': 'rectangle',
'width': 30,
'height': 40
}
]
Run Code Online (Sandbox Code Playgroud)
如何快速检查是否存在shape有价值square?我知道我可以使用for循环来检查每个对象,但有更快的方法吗?
提前致谢!
您可以使用内置函数在一行中执行此操作any:
if any(obj['shape'] == 'square' for obj in shapes):
print('There is a square')
Run Code Online (Sandbox Code Playgroud)
但这相当于for循环方法.
如果您需要获取索引,那么仍然可以在不牺牲效率的情况下执行此操作:
index = next((i for i, obj in enumerate(shapes) if obj['shape'] == 'square'), -1)
Run Code Online (Sandbox Code Playgroud)
然而,这很复杂,只是坚持正常的for循环可能更好.
index = -1
for i, obj in enumerate(shapes):
if obj['shape'] == 'square':
index = i
break
Run Code Online (Sandbox Code Playgroud)
看,没有循环。
import json
import re
if re.search('"shape": "square"', json.dumps(shapes), re.M):
... # "square" does exist
Run Code Online (Sandbox Code Playgroud)
如果要检索与 关联的索引square,则需要使用 迭代它for...else:
for i, d in enumerate(shapes):
if d['shape'] == 'square':
break
else:
i = -1
print(i)
Run Code Online (Sandbox Code Playgroud)
表现
100000 loops, best of 3: 10.5 µs per loop # regex
1000000 loops, best of 3: 341 ns per loop # loop
Run Code Online (Sandbox Code Playgroud)