【问题标题】:How to merge multiple lists into 1 but only those elements that were in all of the initial lists?如何将多个列表合并为 1,但仅合并所有初始列表中的那些元素?
【发布时间】:2021-12-27 23:58:34
【问题描述】:

我需要合并 5 个列表,其中任何列表都可以为空,这样只有所有 5 个初始列表中的项目才会包含在新形成的列表中。

for filter in filters:

    if filter == 'M':
        filtered1 = [] # imagine that this is filled

    if filter == 'V':
        filtered2 = [] # imagine that this is filled

    if filter == 'S':
        filtered3 = [] # imagine that this is filled

    if filter == 'O':
        filtered4 = [] # imagine that this is filled

    if filter == 'C':
        filtered5 = [] # imagine that this is filled

filtered = [] # merge all 5 lists from above

所以现在我需要使用来自所有过滤列表 1-5 的合并数据来过滤列表。我该怎么做?

【问题讨论】:

  • 这称为intersection,通常在sets 上执行,即无序数据没有重复。你能指定如何处理重复和排序吗?
  • 合并列表是否需要按任何特定顺序排列?
  • 如果列表为空,我们是否“合并”?

标签: python list merge


【解决方案1】:

这是最经典的解决方案。

filtered = filter1 + filter2 + filter3 + filter4 + filter5

发生的情况是您将一个列表添加到另一个列表等等......

所以如果 filter1 是 ['a', 'b'] 并且 filter3 是 ['c', 'd'] 并且 filter4 是 ['e'], 那么你会得到:

filtered = ['a', 'b', 'c', 'd', 'e']

【讨论】:

    【解决方案2】:

    给定一些列表xs1,...,xs5

    xss = [xs1, xs2, xs3, xs4, xs5]
    sets = [set(xs) for xs in xss]
    merged = set.intersection(*sets)
    

    这具有merged 可以按任何顺序排列的属性。

    【讨论】:

    • 感谢您是唯一真正理解问题并帮助我的人!加油!
    【解决方案3】:
    f1, f2, f3, f4, f5 = [1], [], [2, 5], [4, 1], [3]
    
    only_merge = [*f1, *f2, *f3, *f4, *f5]
    print("Only merge: ", only_merge)
    
    merge_and_sort = sorted([*f1, *f2, *f3, *f4, *f5])
    print("Merge and sort: ", merge_and_sort)
    
    merge_and_unique_and_sort = list({*f1, *f2, *f3, *f4, *f5})
    print("Merge, unique and sort: ", merge_and_unique_and_sort)
    

    输出:

    Only merge:  [1, 2, 5, 4, 1, 3]
    Merge and sort:  [1, 1, 2, 3, 4, 5]
    Merge, unique and sort:  [1, 2, 3, 4, 5]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2019-04-21
      • 2013-06-01
      • 2016-04-18
      • 1970-01-01
      相关资源
      最近更新 更多