简体   繁体   中英

Python Manipulate list of tuples

I have a list of tuples with the pattern "id" , "text" , "language" like this:

a = [('1', 'hello', 'en'), ('1', 'ciao', 'it'), ('2', 'food', 'en'), ('2', 'cibo', 'it')]

I would like to create a new tuple (like a table) where I have three columns:

"id" , "en_lang" , "it_lang" .

 b = [('1', 'hello', 'ciao'), ('2', 'food', 'cibo')] 

I ask if there is a function that allows me to do this thing.

Basic solution with yeild and zip:

>>> def get_en_it_words(a):
...     for tup1, tup2 in zip(a[0::2], a[1::2]):
...             yield (tup1[0], tup1[1], tup2[1])
... 
>>> a = [('1', 'hello', 'en'),
...  ('1', 'ciao', 'it'),
...  ('2', 'food', 'en'),
...  ('2', 'cibo', 'it')]
>>> list(get_en_it_words(a))
[('1', 'hello', 'ciao'), ('2', 'food', 'cibo')]

This should give you all 'en' words,

>>> a[0::2]
[('1', 'hello', 'en'), ('2', 'food', 'en')]

And other one 'it' words,

>>> a[1::2]
[('1', 'ciao', 'it'), ('2', 'cibo', 'it')]

You can group the items using a defaultdict :

from collections import defaultdict

a = [('1', 'hello', 'en'), ('1', 'ciao', 'it'),
     ('2', 'food', 'en'), ('2', 'cibo', 'it')]

d = defaultdict(list)

for item in a:
    d[item[0]].append(item[1])

This can then be converted to a list of tuples like this:

b = sorted((k,) + tuple(v) for k, v in d.items())

However, you may find the defaultdict useful in its own right, since it allows you to easily look up things by id .

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