使用命名元组获取元组中具有相同名称和值的所有内容(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.
更多推荐
发布评论