简体   繁体   中英

converting tuples to lists in list

I am attempting to convert tuples in lists of a list to lists. More accurately, I just would like to remove the tuples in lists. The original dataset looks like

collections = [[None], [(u'John Demsey ', u' Cornelia Guest')], [(u'Andres White ', u' Margherita Missoni')], [(u'Bibi Monahan, Tuki Br', u'o, ')], [(u'W$

What I would like to achivee is:

collections = [[None], [u'John Demsey ', u' Cornelia Guest'], [u'Andres White ', u' Margherita Missoni']...]

Nevertheless, with the following code, I fail to achieve my goal.

def conv():
    for i in range(len(collections)):
        if collections[i] != None:
            collections[i] = list(collections[i])
        else:
            collections[i][0] = list(collections[i][0])
    return collections[i]

conv = conv()
print(conv)

In the code, I attempted to convert tuples to lists. However, this does not look work. Could someone help me identify the problem and help me correct this? Thank you!!

Try to do it this way:

def conv():
    return [list(c[0]) if isinstance(c[0], tuple) else c for c in collections]

In your code you also return just the last element of list.

Rather go for chain in itertools and list comprehension:

from itertools import chain

[list(i) if i else [i] for i in chain.from_iterable(collections)]

#Out[110]:
#[[None],
# [u'John Demsey ', u' Cornelia Guest'],
# [u'Andres White ', u' Margherita Missoni']]

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