![](/img/trans.png)
[英]Pop up elements based on Index while creating list of lists + the item popped up
[英]creating a list of lists based on same index and item
我有3个这样的清单:
list1 = [1,2]
list2 = [1,1,1,2,2]
list3 = ["comment1", "comment2", "comment3", "comment4", "commment5"]
list2和list3的长度始终相同。
我要完成的工作是通过将list1与list2比较来创建一个新的列表列表,并且当list2中的项目等于list1中的项目时,将list3中具有相同索引的list3中的“评论”附加到新列表中。 因此,在这种情况下,结果应为:
new_list' = [["comment1", "comment2", "comment3"],["comment4", "comment5"]]
我希望我说得足够清楚。
grouped = {}
for k, v in zip(list2, list3):
grouped.setdefault(k, []).append(v)
new_list = [grouped[k] for k in list1]
像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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.