如何访问嵌套列表中的元组元素
我有一个包含嵌套列表的列表,这些嵌套列表里又有元组。这个列表长这样:
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)]
我对“None”是什么类型的并不在意,我只想把它们单独放在一个列表里。
我试过用列表推导式,但我只能拿到元组本身,而不能获取里面的元素。
任何帮助都会很感激。
6 个回答
0
我想428和429是列表中不存在的索引。
所以,针对这个问题
li = [[(' whether', None), (' mated', None),
(' rooster', None), ('', None)],
[(' produced', None), (' without', None),
(' rooster', None), (' infertile', None),
('', None)]
]
print [ [len(subli)*(None,)] for subli in li]
这个代码可以解决这个问题。
[[(None, None, None, None)], [(None, None, None, None, None)]]
你的问题有点奇怪。这样的数据有什么用呢?
8
你可以用和访问列表元素一样的方法来访问元组里的元素:就是用索引。比如说:
lst = [1, (2, 3)]
lst[1][1] # first index accesses tuple, second index element inside tuple
=> 3
11
如果你只是想处理一个包含元组的简单列表,可以用下面的方式:
[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: 理解嵌套列表推导式