简体   繁体   中英

extracting tuple values from list of tuples

I have a list containg tuples of different types like:

[(0, 1, 'BLANK', ''), (0, 2, 'PERSON', 'Deraj'), (3, 8, 'DOB', 'April 27 , 1834'), (9, 11, 'PERSON', 'David Deraj'), (11, 13, 'LOC', 'Pennsylvania'), (16, 19, 'PERSON', 'Mary Deraj')]

How do i get the following output

('Deraj', 'David Deraj')
('Deraj', 'Mary Deraj')

i am trying to use for loop:

for i in l:
    if i[2] == 'PERSON':
        m = list(i[3])

but this doesnt work.

You probably can do it like this(if i understand correctly and you want first member of tuple to be second name of those peoples):

l=[]
for i in l:
  if i[2]=='PERSON':
      temp=i[3].split()
      if len(temp)>1: 
        l.append((temp[1],i[3]))

Assuming that the first record (0, 2, 'PERSON', 'Deraj') has always the first item zero and the second item indicating the number of family members, you can do this in one line.

print [ (entry[3].split()[1], entry[3])
        for entry in data
        if (entry[2] == 'PERSON' and entry[0] > 0) ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM