简体   繁体   English

Python 将列表拆分为重复的块

[英]Python split list into chunks with repetitions

I know that it is possible to do it like this:我知道可以这样做:

test_list = ['1','2','3','4','5','6','7','8','9','10']

x = 3

final_list= lambda test_list, x: [test_list[i:i+x] for i in range(0, len(test_list), x)]

output=final_list(test_list, x)
output is: [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['10']]

but I have a bit different requirements.但我有一些不同的要求。 I should return this:我应该返回这个:

output is: [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['8','9', '10']]

In other words, I should allow repeating of numbers in the final chunk.换句话说,我应该允许在最后一个块中重复数字。 Is there a simple way to do it?有没有简单的方法来做到这一点?

lambda test_list, x: [test_list[min(i,len(test_list)-x):min(i+x,len(test_list))] for i in range(0, len(test_list), x)]

Would probably be more efficient to precalculate len(test_list) though不过,预先计算 len(test_list) 可能会更有效

Pretty much: You said that you wanted the last element to not be the remaining elements, but the last x elements (right?), so that means that if there are less than x elements remaining (ie our index i is greater than or equal to length-x), we do not want to use i as starting index, we want to use length-x.差不多:你说你希望最后一个元素不是剩余的元素,而是最后的 x 个元素(对吗?),所以这意味着如果剩余的元素少于 x 个(即我们的索引 i 大于或等于到length-x),我们不想用i作为起始索引,我们想用length-x。

The second min I used (for the ending index) is not strictly necessary btw, just for cleanliness.顺便说一句,我使用的第二分钟(用于结束索引)并不是绝对必要的,只是为了清洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM