通过滑动 window 将链接分成块
break links into chunks with a sliding window
因此,我试图将列表分成 4 个块,但有一个警告。需要注意的是,我希望列表采用前一个块的最后 2 个元素并将其与接下来的 2 个元素连接起来以生成以下输出:
例如:
Input: text=['one','two','three','four','five','six','seven','eight']
Output: ['one two three four','three four five six', 'five six seven eight']
现在,我有这个:
from itertools import islice
text=['one','two','three','four','five','six','seven','eight']
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
processed = [' '.join(i) for i in window(text,4)]
print(processed)
Output:
['one two three four', 'two three four five', 'three four five six', 'four five six seven', 'five six seven eight']
同样,我的理想输出是:
['one two three four','three four five six', 'five six seven eight']
是这样的吗?
data = 'i ii iii iv v vi vii viii'.split()
print([' '.join(data[i-2:i+2]) for i in range(2, len(data), 2)])
因此,我试图将列表分成 4 个块,但有一个警告。需要注意的是,我希望列表采用前一个块的最后 2 个元素并将其与接下来的 2 个元素连接起来以生成以下输出:
例如:
Input: text=['one','two','three','four','five','six','seven','eight']
Output: ['one two three four','three four five six', 'five six seven eight']
现在,我有这个:
from itertools import islice
text=['one','two','three','four','five','six','seven','eight']
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
processed = [' '.join(i) for i in window(text,4)]
print(processed)
Output:
['one two three four', 'two three four five', 'three four five six', 'four five six seven', 'five six seven eight']
同样,我的理想输出是:
['one two three four','three four five six', 'five six seven eight']
是这样的吗?
data = 'i ii iii iv v vi vii viii'.split()
print([' '.join(data[i-2:i+2]) for i in range(2, len(data), 2)])