【发布时间】:2022-11-12 18:10:34
【问题描述】:
我目前有一个看起来像这样的目录列表:
total_list = [{'email': 'usera@email.com',
'id': 1,
'country': 'UK',
},
{'email': 'userb@email.com',
'id': 2,
'country': 'UK',
},
{'email': 'usera@email.com',
'id': 1,
'country': 'Germany',
},
{'email': 'userc@email.com',
'id': 3,
'country': 'Italy',
},
{'email': 'userd@email.com',
'id': 4,
'country': 'France',
},
{'email': 'userc@email.com',
'id': 3,
'country': 'Netherland',
},....
]
我想主要根据大小对其进行拆分,所以假设新的大小列表是每个列表 3 个项目,但我还想确保所有相同的用户都在同一个新的子列表中。
所以我试图创建的结果是:
list_a = [{'email': 'usera@email.com',
'id': 1,
'country': 'UK',
},
{'email': 'userb@email.com',
'id': 2,
'country': 'UK',
},
{'email': 'usera@email.com',
'id': 1,
'country': 'Germany',
},
]
list_b = [{'email': 'userc@email.com',
'id': 3,
'country': 'Italy',
},
{'email': 'userd@email.com',
'id': 4,
'country': 'France',
},
{'email': 'userc@email.com',
'id': 3,
'country': 'Netherland',
},....
]
显然,在我提供的示例中,用户在列表中的位置非常接近,但实际上他们可以分散得更多。 我正在考虑根据电子邮件对列表进行排序然后拆分它们,但我不确定如果应该组合在一起的项目恰好位于 主列表将被划分。
到目前为止,我尝试过的是:
def list_splitter(main_list, size):
for i in range(0, len(main_list), size):
yield main_list[i:i + size]
# calculating the needed number of sublists
max_per_batch = 3
number_of_sublists = ceil(len(total_list) / max_per_batch)
# sort the data by email
total_list.sort(key=lambda x: x['email'])
sublists = list(list_splitter(main_list=total_list, size=max_per_batch))
问题是用这个逻辑我不能 100%ensure如果有任何具有相同电子邮件值的项目,它们将最终出现在相同的子列表中。由于排序,很可能会发生这种情况,但不确定。
基本上我需要一种方法来确保具有相同email 的项目将始终位于同一子列表中,但拆分的主要条件是子列表大小。
有任何想法吗?
【问题讨论】:
-
您忘记包含解决此问题的尝试。
-
只是把它做得不好,然后改进它。查看如何创建minimal reproducible example 和edit 问题。
-
我的错,现在添加
-
每个子列表是否需要相同的大小?或者特定的子列表可以更小吗?据推测,
email用户的数量将始终小于子列表的大小。如果是这样,这听起来像是 Bin packing problem 的变体。另见:bin packing slides。 -
你说——
I also want to make sure that all the same users will be in the same new sublist.——usera@email.com和userb@email.com有什么关系?