0

如果它们在特定索引处共享一个共同值,那么用另一个子列表扩展一个子列表的最有效方法是什么?如果 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']]

我正在对两个以上的大型列表进行此操作。有没有更短更有效的方法来做到这一点?

4

5 回答 5

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']]
于 2014-01-25T04:09:40.430 回答
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']]
于 2014-01-25T04:12:26.720 回答
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])])
于 2014-01-25T04:14:56.777 回答
0
print [List1[0]+List2[0],List1[1]+list2[1]]
于 2014-01-25T04:15:41.397 回答
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
于 2014-01-25T04:35:33.687 回答