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
161 views
in Technique[技术] by (71.8m points)

python - How can you split a list every x elements and add those x amount of elements to an new list?

I have a list of multiple integers and strings

['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red']

I'm having difficulty separating the list every 5 elements and creating a new list with just 5 elements inside.

However, I don't want 3 different lists, i just want one that changes every time a new 5 elements goes through.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You want something like:

composite_list = [my_list[x:x+5] for x in range(0, len(my_list),5)]

print (composite_list)

Output:

[['-200', ' 0', ' 200', ' 400', ' green'], ['0', '0', '200', '400', ' yellow'], ['200', '0', '200', '400', ' red']]

What do you mean by a "new" 5 elements?

If you want to append to this list you can do:

composite_list.append(['200', '200', '200', '400', 'bluellow'])

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

...