【问题标题】:How to merge two list of list in python如何在python中合并两个列表列表
【发布时间】:2016-12-23 06:18:42
【问题描述】:

输入:

a=[[1,2,3],[4,5,6]]
b=[[5,8,9],[2,7,10]]
c=[]

for i in range(len(a)):
    for j in range(len(a)):
       if a[i][1]==b[j][0]:
           c[i].append(b[j][1])
           c[i].append(b[j][2])
print(c)

IndexError: 列表索引超出范围

输出应该是这样的:

 c=[[1,2,3,7,10],[4,5,6,8,9]]

但是当我在 python 中运行此代码时出现此错误,任何人都可以帮助我,任何帮助将不胜感激

【问题讨论】:

  • 数字 10 和 9 是从哪里来的?
  • 请你解释一下为什么你想要的列表在子列表中有7, 10和8, 9而不是5, 8和2, 7,它们是列表b的一部分跨度>
  • @moinuddin- 抱歉,打错了,我已经编辑过了

标签: python list python-3.x


【解决方案1】:

您可以使用 itertool.chain() 和 list comprehension 表达式来实现此目的:

>>> a=[[1,2,3],[4,5,6]]
>>> b=[[5,8,9],[2,7,10]]

#               v  join the matched sub-lists
#               v                       v  your condition 
>>> [i + list(chain(*[j[1:] for j in b if i[1]==j[0]])) for i in a]
[[1, 2, 3, 7, 10], [4, 5, 6, 8, 9]]

【讨论】:

    【解决方案2】:

    试试这个:

    a=[[1,2,3],[4,5,6]]
    b=[[5,8,9],[2,7,10]]
    c=[]
    
    
    c.append(sorted(list(set(a[0] + b[1]))))
    c.append(sorted(list(set(a[1] + b[0]))))
    print(c)
    

    但请注意,我确信还有其他更优雅的解决方案。

    【讨论】:

      【解决方案3】:
      a=[[1,2,3],[4,5,6]]
      b=[[5,8],[2,7]]
      c=[]
      
      for i in range(len(a)):
          x=a[i]+b[i]
          c.append(x)
      
      print(c)
      

      给你

      【讨论】:

        【解决方案4】:
        a=[[1,2,3],[4,5,6]]
        b=[[5,8,9],[2,7,10]]
        c=[]
        def list_concat_distinct(list1,list2):
            tmp=list1[:]
            tmp.extend([x for x in list2 if x not in list1 ])
            return tmp
        c.append(list_concat_distinct(a[0],b[1]))
        c.append(list_concat_distinct(a[1],b[0]))
        print(c)
        

        希望这可以帮助它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-15
          • 2021-10-07
          • 2021-02-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-01
          相关资源
          最近更新 更多