首页 > 解决方案 > 如何找到具有最大元素数的最大字符串类型子列表(非重复)?

问题描述

我想获得不重复的最大字符串数的子列表。

下面的代码说集合是不可散列的,这是有道理的(TypeError: unhashable type: 'set'),但我找不到解决这个问题的方法。

from collections import Counter
mylist = [{'task'}, {'task', 'time', 'element'}, {'task', 'current', 'time', 'element'}, {'task', 'element'}, {'task'}, {'task'}, {'task', 'element'}, {'task', 'element'}, {'task', 'element'}, {'task', 'push', 'stack', 'element'}]
find_max_lists = max(k for k,v in Counter(mylist).items() if v>1)

输入

[{'task'}, {'task', 'time', 'element'}, {'task', 'current', 'time', 'element'}, {'task', 'element'}, {'task'}, {'task'}, {'task', 'element'}, {'task', 'element'}, {'task', 'element'}, {'task', 'push', 'stack', 'element'}]

输出

[{'task', 'current', 'time', 'element'},{'task', 'push', 'stack', 'element'}]

输入

[{'task'}, {'task', 'time', 'element'}, {'task', 'current', 'time', 'element'}, {'task', 'element'}, {'task'}, {'task'}, {'task', 'element'}, {'task', 'element'}, {'task', 'element'}, {'task', 'current', 'time', 'element'}]

输出

[{'task', 'current', 'time', 'element'}]

标签: python

解决方案


你可以在没有Counter. 由于您的列表包含集合,并且集合中不包含重复的项目,因此您只需检查输入列表中具有最高长度的集合项目,并创建另一个列表,其中包含长度与最高长度匹配的项目。

这里是 :

max_len = len(sorted(mylist, key = lambda x: len(x), reverse = True)[0])
output = [k for k in mylist if len(k)==max_len]
# For the second case where the final list may contain same set-item
uniq_list = [set(x) for x in set(tuple(x) for x in output)]

输出

[{'time', 'task', 'current', 'element'}, {'task', 'push', 'stack', 'element'}]

推荐阅读