Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ''' list_grouping101.py
- group a single list into a list of lists of given size
- '''
- # using a while loop ...
- mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
- n = 0
- size = 3 # desired size of sublist
- newlist = []
- while n < len(mylist):
- sublist = mylist[n : n + size]
- newlist.append(sublist)
- n += size
- print(newlist)
- print('-'*60)
- # using list comprehension ...
- mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
- size = 3
- newlist = [mylist[n : n + size] for n in range(0, len(mylist), size)]
- print(newlist)
- ''' result ...
- [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18]]
- ------------------------------------------------------------
- [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18]]
- '''
- print('-'*60)
- import pprint
- mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
- size = 3
- newlist2 = [mylist[n : n + 3] for n in range(0, len(mylist)) if n < len(mylist)-size]
- pprint.pprint(newlist2)
- '''
- [[0, 1, 2],
- [1, 2, 3],
- [2, 3, 4],
- [3, 4, 5],
- [4, 5, 6],
- [5, 6, 7],
- [6, 7, 8],
- [7, 8, 9],
- [8, 9, 10],
- [9, 10, 11],
- [10, 11, 12],
- [11, 12, 13],
- [12, 13, 14],
- [13, 14, 15],
- [14, 15, 16],
- [15, 16, 17],
- [16, 17, 18],
- [17, 18, 19]]
- '''
Advertisement
Add Comment
Please, Sign In to add comment