Python:如何合并数组中的相同元素?

时间:2014-08-17 10:18:56

标签: python list merge

我有这个数组:

[['Amy', '2'],
 ['Amy', '2'],
 ['Amy', '1'], 
 ['Yoyo', '1'],
 ['Yoyo', '2'],
 ['Yoyo', '2']]

我想这样做:

[['Amy', ['2','2','1'], 
 ['Yoyo',['1','2','2']]

有可能吗?我是否需要先将其列为列表或字典?

3 个答案:

答案 0 :(得分:4)

您可以使用itertools.groupbysortedgroupbyitertools组连续匹配值。

data = [['Amy', '2'],
    ['Amy', '2'],
    ['Amy', '1'], 
    ['Yoyo', '1'],
    ['Yoyo', '2'],
    ['Yoyo', '2']]

import itertools

def extract_key(v):
    return v[0]

# itertools.groupby needs data to be sorted first
data = sorted(data, key=extract_key)

result = [
    [k,[x[1] for x in g]]
    for k, g in itertools.groupby(data, extract_key)
]

答案 1 :(得分:0)

使用itertools.groupby

>>> lst = [['Amy', '2'],
...        ['Amy', '2'],
...        ['Amy', '1'],
...        ['Yoyo', '1'],
...        ['Yoyo', '2'],
...        ['Yoyo', '2']]
>>>
>>> import itertools
>>> [[key, [n for _, n in grp]] for key, grp in
     itertools.groupby(lst, key=lambda x: x[0])]
[['Amy', ['2', '2', '1']],
 ['Yoyo', ['1', '2', '2']]]

答案 2 :(得分:0)

def proc(l = []):
tmp = {}
for e in l:
    if tmp.get(e[0]) is None:
        tmp[e[0]] = []
    tmp[e[0]].append(e[1])
return tmp

如果你可以使用字典。