使用命名元组获取元组中具有相同名称和值的所有内容(get all with same name and value in tuple using named tuple)

编程入门 行业动态 更新时间:2024-10-11 23:23:07
使用命名元组获取元组中具有相同名称和值的所有内容(get all with same name and value in tuple using named tuple)

在python namedtuple中,如何获取具有相同名称的所有值?

例如。 : [tup(a = 1, b=2), tup(a = 2, b=5), tup(a = 3, b=2)]

我怎样才能获得所有或所有b?

另外,是否有可能获得b == 2所有元组?

In python namedtuple, how can I get all values with the same name?

eg. : [tup(a = 1, b=2), tup(a = 2, b=5), tup(a = 3, b=2)]

How can I get all a's or all b's?

Also, is it possible to get all tuples with b == 2 ?

最满意答案

列出对胜利的理解:

all_b_values = [t.b for t in list_of_named_tuples] all_a_values = [t.a for t in list_of_named_tuples]

要么

all_b_2s = [t for t in list_of_named_tuples if t.b == 2]

关于这些列表namedtuple没有任何特定于名称的特定内容; 它们适用于具有共同属性的任何对象序列。

List comprehensions for the win:

all_b_values = [t.b for t in list_of_named_tuples] all_a_values = [t.a for t in list_of_named_tuples]

or

all_b_2s = [t for t in list_of_named_tuples if t.b == 2]

There is nothing namedtuple-specific about these list comprehensions; they work for any sequence of objects with common attributes.

更多推荐

本文发布于:2023-08-04 21:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1422693.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:所有内容   组中   名称   named   tuple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!