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?

1
  • You are looking for all combination (2 items) of inputs?? Commented Apr 4, 2018 at 8:41

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

you can avoid a hard slice with itertools.islice(lst,1,None) for second arg.
[list(pair) for pair in zip(lst, itertools.islice(lst,1,None))]: no extra list creation
I am not totally convinced by islice benefits here.. see stackoverflow.com/a/2485777/9209546
I would assume that there exists a list-length n above which the itertools.islice performs better. Might run some checks later to figure out what n is. Thanks for the link!
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]]

2 Comments

python3 does not have xrange generator
Excellent sliding window!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.