簡體   English   中英

展平元組列表中的列表

[英]Flatten a list inside 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'])
    ]

我想將每個元組中的列表展平,使其成為lst元組的一部分。 我發現這個如何從列表列表中制作平面列表? 但不知道如何使它適合我的情況。

您可以使用解包

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')]

我使用collections中的abc找到了 Deacon 的答案 也值得一試。

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')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM