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

2024-09-30 10:31:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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]

现在,我想要一个函数,它从给定的列表中返回一个特定的namedtuple,并给出一个type。我用for循环编写了这个函数,但是有没有可能做得更好(更快或者没有for循环)?在

^{pr2}$

Tags: 函数applefortypegreenredlistcolor
2条回答

只有在没有重复类型的情况下才能使用此方法。你可以用字典来做这个。在

d = {
"apple" : fruits('apple', 'red', 1.89, 5),
"pear" : fruits('pear', 'green', 2.89, 7),
"banana" : fruits('banana', 'yellow', 2.01, 10)
}

def take_fruit(type)
    return list(d[type])

在这里,字典将type存储为key。这样比较快

您可以使用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

相关问题 更多 >

    热门问题