在python中合并列表项

Merging lists items in Python

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
join list of lists in python
Flatten (an irregular) list of lists in Python

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

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

因此,它非常类似于SQL查询"select*from table,其中smth=smth1"。下面是我的代码,但不太好用。

1
2
3
4
5
6
7
8
    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)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
{(1, 2): set([1, 3, 4, 5, 6, 7, 8, 9, 11]), (5, 6): set([8, 9, 10, 1, 7])}

把你的结构弄出来应该没问题。


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

1
2
3
4
5
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])]