Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

python - Split list into separate but overlapping chunks

Let's say I have a list A

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

I would like to create a new list (say B) using the above list in the following order.

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

i.e. the first 3 numbers as A[0,1,2] and the second 3 numbers as A[2,3,4] and so on.

I believe there is a function in numpy for such a kind of operation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply use Python's built-in list comprehension with list-slicing to do this:

>>> A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> size = 3
>>> step = 2
>>> A = [A[i : i + size] for i in range(0, len(A), step)]

This gives you what you're looking for:

>>> A
[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]

But you'll have to write a couple of lines to make sure that your code doesn't break for unprecedented values of size/step.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...