更新时间:2023-08-26 12:13:16
You could use the next()
function with a generator expression:
fruit_chosen = next((fruit['fruit'] for fruit in lst if fruit['color'] == 'yellow'), None)
这会将 first 水果字典分配为与fruit_chosen
匹配,如果没有匹配,则为None
.
This will assign the first fruit dictionary to match to fruit_chosen
, or None
if there is no match.
或者,如果省略默认值,则如果找不到匹配项,则next()
将提高StopIteration
:
Alternatively, if you leave out the default value, next()
will raise StopIteration
if no match is found:
try:
fruit_chosen = next(fruit['fruit'] for fruit in lst if fruit['color'] == 'yellow')
except StopIteration:
# No matching fruit!
演示:
>>> lst = [{'fruit': 'apple', 'qty':'4', 'color': 'green'},{'fruit': 'orange', 'qty':'6', 'color': 'orange'},{'fruit': 'melon', 'qty':'2', 'color': 'yellow'}]
>>> next((fruit['fruit'] for fruit in lst if fruit['color'] == 'yellow'), None)
'melon'
>>> next((fruit['fruit'] for fruit in lst if fruit['color'] == 'maroon'), None) is None
True
>>> next(fruit['fruit'] for fruit in lst if fruit['color'] == 'maroon')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration