我有一个列表,其中每个元素包含未知数量的集合。(列表中的集合根据用户在程序中所做的选择而有所不同。)现在我想删除集合数量最少的所有元素,只保留集合数量最多的一个或多个元素。
我的列表可能如下所示:
[{'Chocolate'}, {'Chocolate'}, {'JellyBean', 'Chips'}]
在本例中,我只想保留最后一个元素,因为它包含两个集合,其余的只包含一个集合。但有时有几个元素的集合数量最多,然后我想保留所有这些元素。
我试着做一些类似的事情:
if min(len(list)) != max(len(list)):
list.remove(min(len(list)))
但是Python只是说"'int‘object is not iterable",我能理解为什么,但不能理解如何思考。
如果有人帮助我,我会非常感激的!
发布于 2019-04-16 03:39:04
您需要迭代列表一次以确定最大值,然后再次迭代以找到要保留的元素。将会有更花哨的解决方案尽可能以最有效的方式做到这一点,但将更难理解。
example_list = [('Chocolate'), ('Chocolate'), ('JellyBean', 'Chips')]
max_length = 0
for item in example_list:
if len(item) > max_length:
max_length = len(item)
new_list = []
for item in example_list:
if len(item) == max_length:
new_list.append(item)
你也许可以做remove,但是通常Python会因为改变你正在积极迭代的东西而抓狂。
发布于 2019-04-16 03:45:33
为什么不创建一个具有最大元素数的新列表。请在下面进行尝试:
list_of_sets= [{'Chocolate'}, {'Chocolate', 'Candy'}, {'JellyBean', 'Chips'}]
max_len=max(len(s) for s in list_of_sets)
final_list = [s for s in list_of_sets if len(s)==max_len]
final_list
结果:
[{'Candy', 'Chocolate'}, {'Chips', 'JellyBean'}]
https://stackoverflow.com/questions/55696086
复制相似问题