1

I want to split a list into a nest list. The list I have is this:

[1,2,1,3,2]

Now, I want the output to be like this:

[[1,2],[2,1],[1,3],[3,2]]

Is there any possible of doing the output as mentioned above?

Mahir
  • 400
  • 3
  • 15

2 Answers2

6

You can use zip

lst = [1,2,1,3,2]

res = [list(pair) for pair in zip(lst, lst[1:])]
print(res)  # -> [[1, 2], [2, 1], [1, 3], [3, 2]]

Note: the first instance of lst in zip does not have to be sliced since it is the smallest of the two that dictates the number of tuples that will be generated.


As @Jean-FrancoisFabre said in the comments, if the original list is big, you might want to go with a generator instead of a hard slice.

res = [list(pair) for pair in zip(lst, itertools.islice(lst, 1, None))]

The benefit of this approach (or the drawback of the previous one) is that the second list used in zip (lst[1:]) is not created in memory, but you will need to import itertools for it to work.

DTavaszi
  • 192
  • 1
  • 10
Ma0
  • 15,057
  • 4
  • 35
  • 65
2

You're looking for bi-grams. Here is a generic function to generate n-grams from a sequence.

def ngrams(seq, n):
    return [seq[i:i + n] for i in range(len(seq) - n + 1)]

a = [1,2,1,3,2]

print ngrams(a, 2)

# [[1, 2], [2, 1], [1, 3], [3, 2]]
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99