从一个名为元组的列表中的条目我有namedtuples
一个list
如下的Python:如果包含特定属性值
fruits = Fruits['type', 'color', 'weight', 'sweetness']
f1 = fruits('apple', 'red', 1.89, 5)
f1 = fruits('pear', 'green', 2.89, 7)
f1 = fruits('banana', 'yellow', 2.01, 10)
l = [f1, f2, f3]
现在,我想有从列表中返回一个特定namedtuple
功能给出type
。我使用for循环编写了这个函数,但它可以做得更好(更快还是没有for循环)?
def take_fruit(type, all_fruits):
for f in all_fruits:
if f.type == type:
return f
return None
'next((f for all_fruits if for f.type == type),None)'但不知道它是否更快。 –
有几种方法可以做到这一点,但我认为没有比您的变体更快的方法。 如果你想摆脱循环,你可以使用'过滤器'或列表理解。 – Zinki