简体   繁体   English

如何在元组列表中访问元组的元素

[英]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.

相关问题 如何在元组列表中索引元组的最后一个元素 - how to index the last element of a tuple in a list of tuples 如何按第二个元组元素对元组列表进行排序? - How to sort a list of tuples, by the second tuple element? 如何修改元组列表中元组的每个元素 - How to modify each element of a tuple in a list of tuples 在元组的元组列表中通过内部元组查找元素 - Find an element by inner tuple in a list of a tuple of tuples 如何根据另一个列表中元组元素的顺序对元组列表进行排序? - How to sort a list of tuples according to the order of a tuple element in another list? 如何删除属于元组列表的每个元组的第二个元素? - How to remove the 2nd element of every tuple that belongs to a list of tuples? 如何按给定索引处的元素对列表/元组的列表/元组进行排序? - How to sort a list/tuple of lists/tuples by the element at a given index? 对于元组列表中的元素,返回元组中的其他元素 - For element in list of tuples, return other element in tuple 将列表元素与元组列表中的元组元素匹配 - Matching list elements with element of tuple in list of tuples 如何按每个元组中的第一个元素对元组列表进行排序,并选择每个组中最后一个元素最大的元组 - How to sort a list of tuples by the first element in each tuple, and pick the tuple with the largest last element in each group
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM