Mahir
Mahir

Reputation: 400

how to split a list into a nested list in Python 3?

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?

Upvotes: 1

Views: 199

Answers (2)

Ma0
Ma0

Reputation: 15204

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.

Upvotes: 5

Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14124

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]]

Upvotes: 2

Related Questions