How can you split a list every x elements and add

2019-01-17 22:04发布

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 everytime a new 5 elements goes through.

3条回答
SAY GOODBYE
2楼-- · 2019-01-17 22:32

You could do it in a single sentence like

>>> import math
>>> s = ['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red']
>>> [s[5*i:5*i+5] for i in range(0,math.ceil(len(s)/5))]

Then the output should be :

[['-200', ' 0', ' 200', ' 400', ' green'], ['0', '0', '200', '400', ' yellow'], ['200', '0', '200', '400', ' red']]
查看更多
Lonely孤独者°
3楼-- · 2019-01-17 22:35

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'])
查看更多
别忘想泡老子
4楼-- · 2019-01-17 22:45

I feel that you will have to create 1 new list, but if I understand correctly, you want a nested list with 5 elements in each sublist.

You could try the following:

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

new = []
for i in range(0, len(l), 5):
    new.append(l[i : i+5])

This will step through your first list, 'l', and group 5 elements together into a sublist in new. Output:

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

Hope this helps

查看更多
登录 后发表回答