如何访问嵌套lis中的元组元素

2024-06-03 15:54:29 发布

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

我有一个包含元组的嵌套列表。列表如下:

428 [(' whether', None), (' mated', None), (' rooster', None), ('', None)]
429 [(' produced', None), (' without', None), (' rooster', None), (' infertile', None), ('', None)]

我想能够访问元组的“None”元素,每个索引值。我想创建一个新列表,该列表的索引值与下面的相同:

428 [(None, None, None, None)]
429 [(None, None, None, None, None)]

我真的不在乎“无”是什么类型。我只想把它们单独列出来。

我尝试过列表理解,但我只能检索元组本身,而不能检索其中的元素。

任何帮助都将不胜感激。


Tags: none元素类型列表without元组whetherrooster
3条回答

对于只包含元组的单个列表,最简单的方法是:

[x[1] for x in myList]
# [None, None, None, None]

或者如果它总是元组中的最后一个值(如果它包含两个以上的值):

[x[-1] for x in myList]
# [None, None, None, None]

请注意,下面的这些示例使用嵌套列表。它是一个包含元组的列表列表。我想这就是你要找的,因为你展示了两种不同的列表。

使用嵌套的理解列表:

myList =[ [(' whether', None), (' mated', None), (' rooster', None), ('', None)] ,
          [(' produced', None), (' without', None), (' rooster', None), (' infertile', None), ('', None)] ]


print [[x[1] for x in el] for el in myList]
# [[None, None, None, None], [None, None, None, None, None]]

或其他一些变体:

myList =[ [(None, None), (' mated', None), (' rooster', None), ('', None)] ,
              [(' produced', None), (' without', None), (' rooster', None), (' infertile', None), ('', None)] ]

# If there are multiple none values (if the tuple isn't always just two values)
print [ [ [ x for x in z if x == None] for z in el ] for el in myList ]
# [[[None, None], [None], [None], [None]], [[None], [None], [None], [None], [None]]]

# If it's always the last value in the tuple
print [[x[-1] for x in el] for el in myList]
# [[None, None, None, None], [None, None, None, None, None]]

另见: SO: Understanding nested list comprehension

您可以像处理列表元素一样处理元组中的元素:使用索引。例如:

lst = [1, (2, 3)]
lst[1][1] # first index accesses tuple, second index element inside tuple
=> 3

如果你只想得到None如果它存在于元组中:

tuple([None for t in list if None in t])

这将为它所在的每个元组重新创建一个包含None的元组。请注意,如果您想要None的总数,这将不是一个好的解决方案。

相关问题 更多 >