【问题标题】:How to combine python lists, with shared items, into new lists如何将 python 列表与共享项目组合到新列表中
【发布时间】:2013-04-25 19:59:58
【问题描述】:

我是 python 新手,但遇到了障碍。我有一个 python 列表,每行包含一个列表。基本上,我想组合在列表之间共享值的列表。例如, 下面是我的 python 列表目前的样子,以及我希望执行其他命令后数据的样子。

我知道这类问题对于集合和交叉点来说是理想的,但我只是无法让它们正常工作。我还看到了一篇使用索引的帖子,但对我也不起作用。

列表是什么样子的:

[
    ['mary', 'home'],
    ['mary', 'school'],
    ['mary', 'work'],
    ['bob', 'home'],
    ['bob', 'school'],
    ['bob', 'work'],
    ['tom', 'work'],
    ['tom', 'school'],
    ['tom', 'home'],
    ['bill', 'vacation'],
]

我想要的样子:

[
    ['mary', 'bob', 'tom', 'home', 'school', 'work'],
    ['bill', 'vacation'],
]

【问题讨论】:

    标签: python list python-2.7 set intersection


    【解决方案1】:

    您的示例数据表明输入数据中的顺序很重要,这会使情况复杂化。假设它实际上只是一个示例并且顺序 并不 重要,那么集合确实是解决问题的理想方法:

    data = [
        ['mary', 'home'],
        ['mary', 'school'],
        ['mary', 'work'],
        ['bob', 'home'],
        ['bob', 'school'],
        ['bob', 'work'],
        ['tom', 'work'],
        ['tom', 'school'],
        ['tom', 'home'],
        ['bill', 'vacation'],
    ]
    
    combined = []
    
    for subset in [set(d) for d in data]:
        for candidate in combined:
            if not candidate.isdisjoint(subset):
                candidate.update(subset)
                break
        else:
            combined.append(subset)
    

    这使用了 Python 的 for-else 构造,并不是每个人都熟悉。 combined 将包含一个集合列表,因此您可能希望根据您的用例将它们转换为列表。

    【讨论】:

    • 感谢零,效果很好!你是对的,顺序并不重要。
    猜你喜欢
    • 2011-05-20
    • 2023-04-09
    • 2020-07-14
    • 1970-01-01
    • 2022-01-15
    • 2011-03-11
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多