[英]List comprehensions to produce the following List
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?有人可以帮我吗?
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 can use itertools to perform rolling window operations.您可以使用 itertools 执行滚动窗口操作。
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.