我有一个list
的namedtuples
,如下所示
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循环)?在
只有在没有重复类型的情况下才能使用此方法。你可以用字典来做这个。在
在这里,字典将type存储为key。这样比较快
您可以使用
filter
或列表理解使代码变得更短,尽管不一定要更快:相关问题 更多 >
编程相关推荐