What I am trying to do is pretty simple, but I couldn't find how to do it.
From:
list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b']
To:
list1 = ['1', '5', '9']
list2 = ['2', '6', 'a']
list3 = ['3', '7', 'b']
list4 = ['4', '9']
In other words, I need to know how to:
array_split(list, n) will simply split the list into n parts.
To split a string every n characters: Import the wrap() method from the textwrap module. Pass the string and the max width of each slice to the method. The wrap() method will split the string into a list with items of max length N.
Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
The numbered names are a bad idea, and you shouldn't name your own variable list
(it shadows the built-in), but in general you can do something like:
>>> startlist = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b']
>>> n = 4
>>> endlist = [[] for _ in range(n)]
>>> for index, item in enumerate(startlist):
endlist[index % n].append(item)
>>> endlist
[['1', '5', '9'], ['2', '6', 'a'], ['3', '7', 'b'], ['4', '8']]
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
s = []
n = 3
for x in range(n):
s.append(lst[x::n])
print(s)
The specific solution is to use slicing with a stride:
source = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b']
list1 = source[::4]
list2 = source[1::4]
list3 = source[2::4]
list4 = source[3::4]
source[::4]
takes every 4th element, starting at index 0; the other slices only alter the starting index.
The generic solution is to use a loop to do the slicing, and store the result in an outer list; a list comprehension can do that nicely:
def slice_per(source, step):
return [source[i::step] for i in range(step)]
Demo:
>>> source = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b']
>>> source[::4]
['1', '5', '9']
>>> source[1::4]
['2', '6', 'a']
>>> def slice_per(source, step):
... return [source[i::step] for i in range(step)]
...
>>> slice_per(source, 4)
[['1', '5', '9'], ['2', '6', 'a'], ['3', '7', 'b'], ['4', '8']]
>>> slice_per(source, 3)
[['1', '4', '7', 'a'], ['2', '5', '8', 'b'], ['3', '6', '9']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With