Python:如果包含特定属性值,则从命名元组列表中获取条目

标签 python list namedtuple

我有一个 listnamedtuples 如下

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]

现在,我想要一个函数,它从给定 type 的列表中返回一个特定的 namedtuple。我使用 for 循环编写了此函数,但是否可以做得更好(更快或不使用 for 循环)?

def take_fruit(type, all_fruits):
    for f in all_fruits:
        if f.type == type:
           return f
    return None

最佳答案

您可以使用 filter 或列表理解来使代码更短,但不一定更快:

def take_fruit_listcomp(type, all_fruits):
    try:
        return [f for f in all_fruits if f.type == type][0]
    except IndexError:
        return None

def take_fruit_filter(type, all_fruits):
    try:
        # no need for list(..) if you use Python 2
        return list(filter(lambda f: f.type == type, all_fruits))[0]
    except IndexError:
        return None

关于Python:如果包含特定属性值,则从命名元组列表中获取条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45188432/

相关文章:

python - 如何查找列表中的数字是否在列表中两个数字的区间内?

python - 列表排序/修改问题

python - 如何在 python 中标记输入文件中的自然英文文本?

python - 在 python 中写入文件会出现 ascii 错误

python - 为什么在我的代码中 np.array**3 会导致与 (np.array/1)**3 不同的解决方案?

c# - 使用命名元组作为输入参数的 API 调用

python collections.namedtuple() 混淆

Python 在 vi​​rtualenv 之外导入了错误版本的库

Python 切片字符串或添加到列表列表中的字符串

Python 可变 NamedTuple