python - 如何找到具有最大元素数的最大字符串类型子列表(非重复)?
问题描述
我想获得不重复的最大字符串数的子列表。
下面的代码说集合是不可散列的,这是有道理的(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'}]
解决方案
你可以在没有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'}]
推荐阅读
- angular - 正确回答问题时分数不会增加
- android - 如何在android的两个不同活动中显示嵌套的json对象和数组
- oracle - 使用 PL/SQL 从表中检索数据
- python - 如何从新 Lego Mindstorms Robot Inventor 上的自定义 Python 模块导入
- jenkins - 在 Jenkins 声明性管道中访问 Github webhook 有效负载
- r - 使用 grepl & which 查找单元格
- javascript - 错误 [ERR_UNSUPPORTED_DIR_IMPORT]:尝试在本地启动 Nodejs 应用程序时导入目录
- performance - Galting 场景:100 个用户/秒,持续 10 分钟,峰值为 500 个用户/秒,每 30 秒
- php - 将无线电类型的输入发送到 mysql 数据库时出现问题
- c++ - 表达式 (fileNew == NULL) 是否总是正确的?