use*_*766 6 python tuples list
我有一个包含嵌套列表的列表,其中包含元组.该列表如下所示:
428 [(' whether', None), (' mated', None), (' rooster', None), ('', None)]
429 [(' produced', None), (' without', None), (' rooster', None), (' infertile', None), ('', None)]
Run Code Online (Sandbox Code Playgroud)
我希望能够按索引值访问元组的"None"元素.我想创建一个具有相同索引值的新列表,如下所示:
428 [(None, None, None, None)]
429 [(None, None, None, None, None)]
Run Code Online (Sandbox Code Playgroud)
我真的不在乎"无"的类型.我只想将它们作为一个单独的列表.
我已经尝试过列表推导,但我只能自己检索元组,而不是里面的元素.
任何帮助,将不胜感激.
对于包含元组的单个列表,最简单的方法是:
[x[1] for x in myList]
# [None, None, None, None]
Run Code Online (Sandbox Code Playgroud)
或者,如果它始终是元组中的最后一个值(如果它包含两个以上的值):
[x[-1] for x in myList]
# [None, None, None, None]
Run Code Online (Sandbox Code Playgroud)
请注意,下面的这些示例使用嵌套列表.它是包含元组的列表列表.我认为这是你要找的东西,因为你展示了两个不同的列表.
使用嵌套的理解列表:
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]]
Run Code Online (Sandbox Code Playgroud)
或其他一些变化:
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]]
Run Code Online (Sandbox Code Playgroud)
另请参阅: SO:了解嵌套列表理解
您可以使用与列表元素相同的方式处理元组内的元素:使用索引.例如:
lst = [1, (2, 3)]
lst[1][1] # first index accesses tuple, second index element inside tuple
=> 3
Run Code Online (Sandbox Code Playgroud)