Home > Blockchain >  How to make list the elements of a list
How to make list the elements of a list

Time:12-21

I have to make a list of the elements of a list. I have the list: n=[1,2,3,4,5,6] and I want to create:

n=[[1],[2],[3],[4],[5],[6]]
n=[[1,2],[3,4],[5,6]]
n=[[1,2,3],[4,5,6]]

I can do the first one using map(list,n), but what about the others? Also if I want to create a list for each couple of elements, like:

n=[[1,2] [2,3] [3,4] [4,5] [5,6]]

How can I do that?

CodePudding user response:

>>> s = [1,2,3,4,5,6]
>>> s1 = [[each] for each in s]
>>> s1
[[1], [2], [3], [4], [5], [6]]

>>> s2 = [[each,each 1] for each in s[:2:]]
>>> s2

[[1, 2], [2, 3]]
>>> s2 = [[each,each 1] for each in s[::2]]
>>> s2
[[1, 2], [3, 4], [5, 6]]
>>> s2 = [[each, each 1, each 2] for each in s[::3]]
>>> s2

[[1, 2, 3], [4, 5, 6]]
>>> 

CodePudding user response:

You can use a chunkify method using some list comprehension, iter and zip trick:

def chunkify(l, size):
    it = iter(l)
    return [list(e) for e in zip(*[it for _ in range(size)])]

example:

n=[1,2,3,4,5,6]
for size in range(1, 4):
    print(chunkify(n, size))

outputs:

[[1], [2], [3], [4], [5], [6]]
[[1, 2], [3, 4], [5, 6]]
[[1, 2, 3], [4, 5, 6]]
  • Related