2

For example, if I had the list:

list_a = [5, 2, 30, 6, 17]

The lists I want to obtain relate to the len(list_b), for example:

list_b = [40, 90]

So the lists I need to create are:

[5, 2]
[2, 30]
[30, 6]
[6, 17]

How can I slice or use a loop to do this?

jpp
  • 159,742
  • 34
  • 281
  • 339
crtbk
  • 35
  • 4
  • what if the len(list_b) == 3? what is the intersection len of two adjacent lists in the result? – Keloo Apr 25 '18 at 11:38
  • 2
    @DeepSpace list_a=[1,2,3,4,5] len(list_b) == 3, result==[1,2,3],[3,4,5] or [1,2,3],[2,3,4],[3,4,5]? – Keloo Apr 25 '18 at 11:45
  • @Keloo the result should ==[1,2,3],[2,3,4],[3,4,5] – crtbk Apr 25 '18 at 11:47
  • @crtbk I voted for a reopen but until this happens, you can work with `res = [list_a[i:i+size] for i in range(len(list_a)-size+1)]` assuming `size = len(list_b)` – Ma0 Apr 25 '18 at 12:07

1 Answers1

0

Here is one solution using itertools.islice. This reduces the need to build lists which might otherwise be used to feed a zip function.

from itertools import islice

a = [5, 2, 30, 6, 17]
b = [40, 90, 20]

n = len(b)

slices = (islice(a, i, None) for i in range(1, n))
res = list(zip(*(a, *slices)))

# [(5, 2, 30), (2, 30, 6), (30, 6, 17)]
jpp
  • 159,742
  • 34
  • 281
  • 339