根据相同的索引和项创建列表列表

时间:2015-11-20 22:11:57

标签: python list

我有3个这样的名单:

list1 = [1,2]
list2 = [1,1,1,2,2]
list3 = ["comment1", "comment2", "comment3", "comment4", "commment5"]

list2和list3的长度始终相同。

我想要完成的是通过将list1与list2进行比较来创建新的列表列表,当list2中的项目等于list1中的项目时,附加"注释"在list3中,list2中的索引与新列表中的索引相同。 所以在这种情况下,结果应该是:

new_list' = [["comment1", "comment2", "comment3"],["comment4", "comment5"]]

我希望我说得够清楚......

2 个答案:

答案 0 :(得分:1)

grouped = {}
for k, v in zip(list2, list3):
    grouped.setdefault(k, []).append(v)
new_list = [grouped[k] for k in list1]

答案 1 :(得分:0)

与Python中的许多问题一样,这应该通过zip来解决:

# Make result list
new_list = [[] for _ in range(len(list1))]
# Make cheap lookup to find the appropriate list to append to
new_lookup = dict(zip(list1, new_list))
for addkey, comment in zip(list2, list3):
    new_lookup[addkey].append(comment)
相关问题