[英]How to access element of Tuple in a list of tuples
I am new to Python and doing some hands on. 我是Python的新手并且正在做一些事情。
I have a list of tuples of tuples (each tuple is having 3 sub-tuples) as below: 我有一个元组元组列表(每个元组有3个子元组)如下:
ABC = [ (('The', 'AT'), ('Fulton', 'NP-TL'), ('County', 'NN-TL')),
(('Fulton', 'NP-TL'), ('County', 'NN-TL'), ('Grand', 'JJ-TL')),
(('County', 'NN-TL'), ('Grand', 'JJ-TL'), ('Jury', 'NN-TL')),
(('Grand', 'JJ-TL'), ('Jury', 'NN-TL'), ('said', 'VBD')),
(('Jury', 'NN-TL'), ('said', 'VBD'), ('Friday', 'NR')) ]
I need to extract the second value of sub-tuple in each tuple ie 3 values and get them in a Tuple , which will be added in list. 我需要在每个元组中提取子元组的第二个值,即3个值,并将它们放入元组中,这将被添加到列表中。
Please assist how to get this. 请协助如何获得这个。
Expected result: 预期结果:
I need a new list derived from it as: 我需要一个从它派生的新列表:
ABC_subset = [('AT','NP-TL', 'NN-TL'),
('NP-TL','NN-TL', 'JJ-TL'),
('NN-TL','JJ-TL', 'NN-TL'),
('JJ-TL','NN-TL', 'VBD'),
('NN-TL','VBD', 'NR')]
I am trying something like this: 我正在尝试这样的事情:
ABC_subset = [(t[1],u[1],v[1]) for tup in ABC for t,u,v in tup]
But it is not giving the expected answer. 但它没有给出预期的答案。
[(x[1] for x in y) for y in your_list]
Let's say your first list is orig
and the second list that you want is newlist
. 假设你的第一个列表是orig
,你想要的第二个列表是newlist
。 It can be done very simply with list comprehensions: 它可以通过列表推导非常简单地完成:
newlist = [tuple(j[1] for j in i) for i in orig]
Essentially, iterate through each row i
of orig
, and extract the second element from each tuple j
in that row. 本质上,遍历orig
每一行i
,并从该行中的每个元组j
中提取第二个元素。
Use a List Comprehension like: 使用列表理解,如:
output = [tuple(j[1] for j in i) for i in inputlist]
You will need to convert the second expression to a tuple as else it would output a generator object 您将需要将第二个表达式转换为元组,否则它将输出生成器对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.