python - How can you split a list every x elements and add those x amount of elements to an new list? -
i have list of multiple integers , strings ['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red'] i'm having difficulty separating list every 5 elements , creating new list 5 elements inside. however, don't want 3 different lists, want 1 changes everytime new 5 elements goes through.
you want like:
composite_list = [my_list[x:x+5] 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 mean "new" 5 elements?
if want append list can do:
composite_list.append(['200', '200', '200', '400', 'bluellow'])
Comments
Post a Comment