如果列表包含相同的元素,则在嵌套列表中合并列表? [英] Combining lists within a nested list, if lists contain the same element?
问题描述
我有一个嵌套列表,其结构与此类似,只是它的长度明显更长:
I have nested list that has a structure similar to this, except it's obviously much longer:
mylist = [ ["Bob", "12-01 2:30"], ["Sal", "12-01 5:23"], ["Jill", "12-02 1:28"] ]
我的目标是创建另一个嵌套列表,以组合所有具有相同日期的元素.因此,需要以下输出:
My goal is to create another nested lists that combines all elements that have the same date. So, the following output is desired:
newlist = [ [["Bob", "12-01 2:30"], ["Sal", "12-01 5:23"]], [["Jill", "12-02 1:28"]] ]
上面,所有日期为12-01的项目(无论时间如何)都被合并,而12-02的所有元素都被合并.
Above, all items with the date 12-01, regardless of time, are combined, and all elements of 12-02 are combined.
在过去的1个小时里,我一直在认真研究如何执行此操作,但是找不到任何东西.此外,我是编程的初学者,所以我不够熟练,无法尝试创建自己的解决方案.因此,请不要以为我没有尝试进行研究或亲自尝试解决此问题.我将在下面添加一些链接作为我的研究示例:
I've sincerely been researching how to do this for the past 1 hour and can't find anything. Furthermore, I'm a beginner at programming, so I'm not skilled enough to try to create my own solution. So, please don't think that I haven't attempted to do research or put any effort into trying this problem myself. I'll add a few links as examples of my research below:
串联两个列表没有嵌套for循环的Python中明智的Strings元素
How to merge lists into a list of tuples?
推荐答案
在日期时间之前使用dict或orderdict(如果排序很重要)组数据.
Use dict or orderdict(if the sort is important) group data by the date time .
from collections import defaultdict # use defaultdict like {}.setdefault(), it's very facility
mylist = [["Bob", "12-01 2:30"], ["Sal", "12-01 5:23"], ["Jill", "12-02 1:28"]]
record_dict = defaultdict(list)
# then iter the list group all date time.
for data in mylist:
_, time = data
date_time, _ = time.split(" ")
record_dict[date_time].append(data)
res_list = list(record_dict.values())
print(res_list)
输出:
[[['Bob', '12-01 2:30'], ['Sal', '12-01 5:23']], [['Jill', '12-02 1:28']]]
这篇关于如果列表包含相同的元素,则在嵌套列表中合并列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!