How Can You Split A List Every X Elements And Add Those X Amount Of Elements To An New List?
Solution 1:
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'])
Solution 2:
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
Solution 3:
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']]
Solution 4:
There is a slightly different approach that I detailed in a previous answer using zip
. The previous answer was closed as a duplicate of this answer so I add my answer here for reference.
You can chunk up a list using iter
and zip
.
def chunk(lst, n):
return zip(*[iter(lst)]*n)
Example:
In []:
data = ['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400',
' yellow', '200', '0', '200', '400', ' red']
for l in chunk(data, 5):
print(l)
Out[]:
('-200', ' 0', ' 200', ' 400', ' green')
('0', '0', '200', '400', ' yellow')
('200', '0', '200', '400', ' red')
if you want them in a list then:
In []:
list(chunk(data, 5))
Out[]:
[('-200', ' 0', ' 200', ' 400', ' green'), ('0', '0', '200', '400', ' yellow'),
('200', '0', '200', '400', ' red')]
Explanation:
def chunk(lst, n):
it = iter(lst) # creates an iterator
its = [it]*n # creates a list of n it's (the same object)
return zip(*its) # unpack the list as args to zip(), e.g. when `n=3` - zip(it, it, it)
Because the zip()
is operating on the same iterator n
times then it will chunk the original lst
into groups of n
.
In Py3, this is lazy (zip()
returns an iterator), so will only create the chunks of n
as you need them, which could be important if you have a big original list.
Post a Comment for "How Can You Split A List Every X Elements And Add Those X Amount Of Elements To An New List?"