python - 如果列表包含相同的元素,则在嵌套列表中组合列表?

标签 python python-3.x list

我有一个嵌套列表,其结构与此类似,但它显然要长得多:

mylist = [ ["Bob", "12-01 2:30"], ["Sal", "12-01 5:23"], ["Jill", "12-02 1:28"] ]

我的目标是创建另一个嵌套列表,组合具有相同日期的所有元素。因此,需要以下输出:

newlist = [  [["Bob", "12-01 2:30"], ["Sal", "12-01 5:23"]], [["Jill", "12-02 1:28"]]  ]

上面,日期为 12-01 的所有项目(无论时间如何)都被合并,并且 12-02 的所有元素都被合并。

在过去的 1 小时里,我一直在真诚地研究如何做到这一点,但找不到任何东西。此外,我是编程初学者,所以我没有足够的技能来尝试创建自己的解决方案。所以,请不要认为我自己没有尝试做研究或付出任何努力来尝试这个问题。我将在下面添加一些链接作为我的研究示例:

Collect every pair of elements from a list into tuples in Python

Create a list of tuples with adjacent list elements if a condition is true

How do I concatenate two lists in Python?

Concatenating two lists of Strings element wise in Python without Nested for loops

Zip two lists together based on matching date in string

How to merge lists into a list of tuples?

最佳答案

使用 dict 或 orderdict(如果排序很重要)按日期时间对数据进行分组。

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)

输出:
[[['鲍勃', '12-01 2:30'], ['萨尔', '12-01 5:23']], [['吉尔', '12-02 1:28' ]]]

关于python - 如果列表包含相同的元素,则在嵌套列表中组合列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59366840/

相关文章:

python - 通过python编辑配置文件

python - 如何以格式化字符串打开文件?

python - 从 Python 3 中的文件生成的列表中查找字符串

python - python 列表中每个元素的唯一索引值

python - 使用 : python manage. py [something] 或 ./manage.py [something] 有什么不同吗

python - 如何将网页保存为文本文件[Python]

python - 从字典列表中获取键值

python 2 打印带有浮点格式且没有行返回的数组

python - 有很多页面的 Django 分页器

C++,插入 List<Class*>,vector<Class> 迭代器