I have list like this List = ['4', '4', '1', '2', '3', '2', '4', '1']
and i need to transform in list like List = [["4","4"],['1','2'],['3','2'],['4','1']]
.
Asked
Active
Viewed 85 times
-2

VladilsavOl
- 21
- 2
-
Try searching for similar questions before asking your own: https://stackoverflow.com/questions/2130016/splitting-a-list-into-n-parts-of-approximately-equal-length – otocan Feb 12 '20 at 12:53
-
Try something first before posting your question as an assignment to the reader. – Jongware Feb 12 '20 at 12:55
2 Answers
1
itertools
provides a recipe, which can split an iterable into fixed-size blocks:
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)

Masklinn
- 34,759
- 3
- 38
- 57
0
Ugly but it works...
def eqsplit(aList,partSize):
return [aList[partSize*n:partSize*(n+1)] for n in range(0,int(len(aList)/partSize)+(1 if len(aList)%partSize else 0))]

kpie
- 9,588
- 5
- 28
- 50