List comprehensions to produce the following List

Viewed 85

Write List comprehensions to produce the following List pattern:

[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
a= [2,3,4,5]
pattern = [ ]
l = [ ] 
[pattern.append(i+j) for i in a for j in range(0,4)]
print(pattern)

With this code I could just print the output without putting them in the required pattern. Could someone help me out?

3 Answers

You could do:

a = [2, 3, 4, 5]
pattern = [[ai + j for ai in a] for j in range(0, 4)]
print(pattern)

Output

[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]

You could cast a range to a list for each element in a:

>>> a = [2, 3, 4, 5]
>>> sub_list_size = 4
>>> pattern = [list(range(x, x + sub_list_size)) for x in a]
>>> pattern
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]

You can use itertools to perform rolling window operations.

from itertools import islice, tee

l = [i for i in range(2,10)]
#[2, 3, 4, 5, 6, 7, 8, 9]

def sliding_window(iterable, size):
    iterables = tee(iter(iterable), size)
    window = zip(*(islice(t, n, None) for n,t in enumerate(iterables)))
    yield from window
    
[i for i in sliding_window(l,4)]
[(2, 3, 4, 5), (3, 4, 5, 6), (4, 5, 6, 7), (5, 6, 7, 8), (6, 7, 8, 9)]
Related