简体   繁体   中英

Flatten a list inside list of tuples

I have the following list of tuples.

lst = 
    [
        ('LexisNexis', ['IT Services and IT Consulting ', ' New York City, NY']),
        ('AbacusNext', ['IT Services and IT Consulting ', ' La Jolla, California']), 
        ('Aderant', ['Software Development ', ' Atlanta, GA']),
        ('Anaqua', ['Software Development ', ' Boston, MA']),
        ('Thomson Reuters Elite', ['Software Development ', ' Eagan, Minnesota']),
        ('Litify', ['Software Development ', ' Brooklyn, New York'])
    ]

I want to flatten the lists in each tuple to be part of the tuples of lst . I found this How do I make a flat list out of a list of lists? but have no idea how to make it adequate to my case.

You can use unpacking :

lst = [('LexisNexis', ['IT Services and IT Consulting ', ' New York City, NY']),
       ('AbacusNext', ['IT Services and IT Consulting ', ' La Jolla, California']), 
       ('Aderant', ['Software Development ', ' Atlanta, GA']),
       ('Anaqua', ['Software Development ', ' Boston, MA']),
       ('Thomson Reuters Elite', ['Software Development ', ' Eagan, Minnesota']),
       ('Litify', ['Software Development ', ' Brooklyn, New York'])]

output = [(x, *l) for (x, l) in lst]

print(output)
# [('LexisNexis', 'IT Services and IT Consulting ', ' New York City, NY'),
#  ('AbacusNext', 'IT Services and IT Consulting ', ' La Jolla, California'),
#  ('Aderant', 'Software Development ', ' Atlanta, GA'),
#  ('Anaqua', 'Software Development ', ' Boston, MA'),
#  ('Thomson Reuters Elite', 'Software Development ', ' Eagan, Minnesota'),
#  ('Litify', 'Software Development ', ' Brooklyn, New York')]

I've found the answer by Deacon using abc from collections . It is worth to try it too.

from collections import abc

def flatten(obj):
    for o in obj:
        # Flatten any iterable class except for strings.
        if isinstance(o, abc.Iterable) and not isinstance(o, str):
            yield from flatten(o)
        else:
            yield o

[tuple(flatten(i)) for i in lst]
Out[47]: 
[('LexisNexis', 'IT Services and IT Consulting ', ' New York City, NY'),
 ('AbacusNext', 'IT Services and IT Consulting ', ' La Jolla, California'),
 ('Aderant', 'Software Development ', ' Atlanta, GA'),
 ('Anaqua', 'Software Development ', ' Boston, MA'),
 ('Thomson Reuters Elite', 'Software Development ', ' Eagan, Minnesota'),
 ('Litify', 'Software Development ', ' Brooklyn, New York')]

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