python - 比较列表中的相邻变量并重新格式化输入
问题描述
inp = [1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 14, 17, 20, 25,27,28,29,31]
预期输出:如果相邻变量是串联的,则用连字符填充。如果没有,请附加给定的数字。
Expected Output = [1-3,5,7-12,14,17,20,25,27-29,31]
我使用下面的代码取了一个相邻的数字。但不满足要求。
inp = [1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 14, 17, 20, 25,27,28,29,31]
for x,y in zip(inp[::],inp[1::]):
print(x,y)
解决方案
您可以使用itertools.groupby
:
from itertools import groupby
lst = [1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 14, 17, 20, 25,27,28,29,31]
out = []
for _, g in groupby(enumerate(lst), lambda k: k[1]-k[0]):
g = [*g]
if len(g) == 1:
out.append(str(g[0][1]))
else:
out.append('{}-{}'.format(g[0][1], g[-1][1]))
print(out)
印刷:
['1-3', '5', '7-12', '14', '17', '20', '25', '27-29', '31']
推荐阅读
- google-chrome - 在 Chrome 中打开位于 IE 中的 Href 链接
- r - 制作 R 脚本。特殊字符的问题
- python - Python:从公共 API 请求批量历史天气数据
- spring - 使用 S3 后端从 Spring Cloud Config Server 提供纯文本文件
- azure - 如何在 Azure 上部署 laravel 应用程序
- hive - 有没有办法将数据预加载到 PowerBI 报表服务器中的报表中?
- vue.js - 从“模式:哈希”更改为“模式:历史”的问题
- python - Error while working on authentication of one drive "KeyError: 'expires_in'"
- tensorflow - 将 Tensorboard 中的 x 轴相对时间更改为分钟
- javascript - 在 componentDidMount() 方法中状态更改后,DOM 中没有渲染