vegaseat

group list into a list of lists of given size

Mar 13th, 2015
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. ''' list_grouping101.py
  2. group a single list into a list of lists of given size
  3. '''
  4.  
  5. # using a while loop ...
  6. mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
  7. n = 0
  8. size = 3  # desired size of sublist
  9. newlist = []
  10. while n < len(mylist):
  11.     sublist = mylist[n : n + size]
  12.     newlist.append(sublist)
  13.     n += size
  14.  
  15. print(newlist)
  16.  
  17. print('-'*60)
  18.  
  19. # using list comprehension ...
  20. mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
  21. size = 3
  22. newlist = [mylist[n : n + size] for n in range(0, len(mylist), size)]
  23. print(newlist)
  24.  
  25. ''' result ...
  26. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18]]
  27. ------------------------------------------------------------
  28. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18]]
  29. '''
  30. print('-'*60)
  31.  
  32. import pprint
  33. mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
  34. size = 3
  35. newlist2 = [mylist[n : n + 3] for n in range(0, len(mylist)) if n < len(mylist)-size]
  36. pprint.pprint(newlist2)
  37.  
  38. '''
  39. [[0, 1, 2],
  40. [1, 2, 3],
  41. [2, 3, 4],
  42. [3, 4, 5],
  43. [4, 5, 6],
  44. [5, 6, 7],
  45. [6, 7, 8],
  46. [7, 8, 9],
  47. [8, 9, 10],
  48. [9, 10, 11],
  49. [10, 11, 12],
  50. [11, 12, 13],
  51. [12, 13, 14],
  52. [13, 14, 15],
  53. [14, 15, 16],
  54. [15, 16, 17],
  55. [16, 17, 18],
  56. [17, 18, 19]]
  57.  
  58. '''
Advertisement
Add Comment
Please, Sign In to add comment