python - 在 Python 中将序列拆分为单个步骤的最优雅方法

标签 python python-3.x list split chunks

假设我有一个从 0 到 9 的列表:

lst = list(range(10))

我想将它分成 2 个单独的步骤。我设法编写了以下工作代码:

res = [[] for _ in range(len(lst) - 1)]
for i, x in enumerate(lst):
    if i < len(lst) - 1:
        res[i].append(x)
    if i > 0:
        res[i-1].append(x)

>>> print(res)
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]

但我觉得应该有更优雅的编码方式。有什么建议吗?

最佳答案

您可以归纳为 n 个步骤:

def steps(lst, n=2):
    return [[*x] for x in zip(*(lst[i:] for i in range(n)))]

steps(range(10), 2)
# [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]
steps(range(10), 3)
# [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9]]

关于python - 在 Python 中将序列拆分为单个步骤的最优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69288482/

相关文章:

r - 将列表变为 "list of lists"

Python 花旗骰 : Creating a list with sets. 意外类型

python - numpy.save() 内的 Pickle TypeError

python - 如何从元组填充 QTreeWidget?

python - 按缺失对过滤数据帧

python - 使用 *args 而不将参数放入元组中?

python - 如何用Python实现EXCEL的查找功能

VB.NET 如果我想锁定多个东西,我是否需要多个 SyncLocks?

Python asyncio 任务排序

java - 如何读取 Elasticsearch 快照