gpt4 book ai didi

python - 如何在numpy中执行重复填充?

转载 作者:行者123 更新时间:2023-12-03 23:34:57 24 4
gpt4 key购买 nike

我有可变长度的数据,想通过重复较短的样本将其打包成最大样本 len 大小的批处理。

例如从这个

[[0, 1, 2, 3, 4], [0, 1, 2], [2, 2, 3]]

做这个

[[0, 1, 2, 3, 4], [0, 1, 2, 0, 1], [2, 2, 3, 2, 2]]

最佳答案

不是 numpy 答案,但您可以使用 itertools 做到这一点:

from itertools import cycle, islice

lst = [[0, 1, 2, 3, 4], [0, 1, 2], [2, 2, 3]]

n = max(len(item) for item in lst)
res = list(list(islice(cycle(item), n)) for item in lst)
print(res) # [[0, 1, 2, 3, 4], [0, 1, 2, 0, 1], [2, 2, 3, 2, 2]]

我在哪里使用 cycle循环遍历子列表和 islice获取第一个 n 元素。

关于python - 如何在numpy中执行重复填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60972141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com