[英]get all with same name and value in tuple using named tuple
In python namedtuple, how can I get all values with the same name? 在python namedtuple中,如何获取具有相同名称的所有值?
eg. 例如。 : [tup(a = 1, b=2), tup(a = 2, b=5), tup(a = 3, b=2)]
: [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? 如何获得全部a或全部b?
Also, is it possible to get all tuples with b == 2
? 另外,是否有可能获得b == 2
所有元组?
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; 这些列表namedtuple
没有特定于namedtuple
内容。 they work for any sequence of objects with common attributes. 它们适用于具有公共属性的任何对象序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.