合并在Python中列出项目

时间:2012-03-29 12:23:03

标签: python list merge

  

可能重复:
  join list of lists in python
  Flatten (an irregular) list of lists in Python

所以,我需要使用python合并列表的某些部分,但仍然无法获得有效的解决方案。 例如,我有一个arr列表,我想得到

[
   [1, 2, (3, 4, 5, 6, 7, 8, 9, 11, 1)], 
   [5, 6, (7, 8, 9, 10, 1)]
] 

因此,它与sql查询“select * from table smth = smth1”非常相似。下面是我的代码,但是效果不好。

    arr = [[1, 2, 3, 4, 5, 6], [1, 2, 6, 7, 8, 9], [1, 2, 11, 1, 5, 9], [5, 6, 7, 8, 9, 10], [5, 6, 1, 1, 1, 1]]
    result = []
    for i in arr[:]:
        for j in arr[:]:
            if i[0] == j[0] and i[1] == j[1] and i != j:
                a = i[:]
                a[2:] = zip(i[2:], j[2:])
                result.append(a)

2 个答案:

答案 0 :(得分:1)

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

data = {}
for sub in arr:
    key = tuple(sub[:2])
    data[key] = data.get(key, set()).union(sub[2:])

print data

这会产生类似:

{(1, 2): set([1, 3, 4, 5, 6, 7, 8, 9, 11]), (5, 6): set([8, 9, 10, 1, 7])}

使你的结构不应该没问题。

答案 1 :(得分:0)

如果结果元组的顺序无关紧要,这里有一个使用itertools.groupby()的解决方案

from itertools import groupby

arr = [[1, 2, 3, 4, 5, 6], [1, 2, 6, 7, 8, 9], [1, 2, 11, 1, 5, 9], [5, 6, 7, 8, 9, 10], [5, 6, 1, 1, 1, 1]]
arr.sort()
print [[group[0][0], group[0][1], tuple(set(sum([sublist[2:] for sublist in group[1]], [])))] for group in groupby(arr, lambda l: l[0:2])]