如果两个子列表中的同一索引共享一个公共ID,如何将一个子列表扩展到另一个子列表?

时间:2014-01-25 04:02:23

标签: python list defaultdict

如果一个子列表与另一个子列表在特定索引中共享一个共同值,那么将其扩展的最有效方法是什么?如果List1的索引0处的值等于List2的索引0的值,我想将两个子列表合并在一起。

List1 = [['aaa','b','c'],['ddd','e','f']]
List2 = [['aaa','1','2'],['ddd','3','4']]

期望的输出:

[['aaa','b','c','aaa','1','2'],['ddd','e','f','ddd','3','4']]

我的黑客:

from collections import defaultdict

Keys2 = map(lambda x: x[0], List2) #returns ['aaa','ddd']
List2_of_Tuples = zip(Keys,List2) #returns [('aaa',['aaa','1','2']),('ddd',['ddd','3','4'])]

Keys1 = map(lambda x: x[0], List1) 
List1_of_Tuples = zip(Keys,List1)

Merged_List_of_Tuples = List1_of_Tuples + List2_of_Tuples
d = defaultdict(list)
for k,v in Merged_List_of_Tuples:
    d[k].append(v)

Desired_Result = map(lambda x: [item for sublist in x[1] for item in sublist],d.items())

返回:

[['aaa', 'b', 'c', 'aaa', '1', '2'], ['ddd', 'e', 'f', 'ddd', '3', '4']]

我这样做是为了两个以上的大型名单。是否有更短的更有效的方法来做到这一点?

5 个答案:

答案 0 :(得分:2)

我只会使用列表理解。

List1 = [['aaa','b','c'],['ddd','e','f']]
List2 = [['aaa','1','2'],['ddd','3','4']]

new_list = [a + b for a, b in zip(List1, List2) if a[0] == b[0]]

结果:

>>> new_list
[['aaa', 'b', 'c', 'aaa', '1', '2'], ['ddd', 'e', 'f', 'ddd', '3', '4']]

答案 1 :(得分:1)

list1,list2 = [['aaa','b','c'],['ddd','e','f']],[['aaa','1','2'],['ddd','3','4']]

from itertools import chain, groupby
from operator import itemgetter
get_first, result = itemgetter(0), []
for key, grp in groupby(sorted(chain(list1, list2), key = get_first), get_first):
    result.append([item for items in grp for item in items])
print result

<强>输出

[['aaa', 'b', 'c', 'aaa', '1', '2'], ['ddd', 'e', 'f', 'ddd', '3', '4']]

答案 2 :(得分:0)

我认为List1不一定在List2中有匹配的项目吗?

怎么样:

list2_keys = map(lambda x:x[0],List2)
for i,l in enumerate(List1):
    if l[0] in list2_keys:
        List1[i].extend(List2[list2_keys.index(l[0])])

或者如果您不想修改列表:

list2_keys = map(lambda x:x[0],List2)
new_list = []
for i,l in enumerate(List1):
    if l[0] in list2_keys:
        new_list.append(List1[i]+List2[list2_keys.index(l[0])])

答案 3 :(得分:0)

print [List1[0]+List2[0],List1[1]+list2[1]]

答案 4 :(得分:0)

这是另一种方法:

List1 = [['aaa','b','c'],['ddd','e','f'],['a','b'],['k','l']]
List2 = [['aaa','1','2'],['ddd','3','4'],['c','d']]
new_list = []

for (index, elem) in enumerate(List1):
    try:
        if elem[0] == List2[index][0]:
            new_list.append(elem+List2[index])
    except IndexError:
        break

print new_list