Python 基于循环条件的Zip运算符参数

Python 基于循环条件的Zip运算符参数,python,for-loop,functional-programming,Python,For Loop,Functional Programming,我想增加基于for循环在字符串中压缩的项目数 例如,这就是代码 s = "abcde" for i in range(1, len(s)): #if i = 1, then this should be the code statement l = zip(s, s[1:]) #list(l) = [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')] #if i = 2, then l = zip(s, s[

我想增加基于for循环在字符串中压缩的项目数

例如,这就是代码

 s = "abcde"

 for i in range(1, len(s)):

    #if i = 1, then this should be the code statement
    l = zip(s, s[1:]) #list(l) = [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')]

    #if i = 2, then 
    l = zip(s, s[1:], s[2:]) #list(l) = [('a', 'b', 'c'), ('b', 'c', 'd'), ('c', 'd', 'e')]

    #if i = 3, then 
    l = zip(s, s[1:], s[2:], s[3:]) #list(l) = [('a', 'b', 'c', 'd'), ('b', 'c', 'd', 'e')]
请注意,对于任何给定的i,zip操作符中都有i+1个iterables

是一个创建s的切片列表的。 对于n=2,它将创建列表[s[0]、s[1]、s[2:]。 它可以写为常规for循环:

l = []
for i in range(0,n+1):
    #print(i, 's[{}:]'.format(i))
    l.append(s[i:])
使用解决方案中使用的常规for循环将是:

for n in range(1, len(s)):
    #print('n:{}'.format(n), '**********')
    l = []
    for i in range(0, n+1):
        l.append(s[i:])
        #print(l)
    print(list(zip(*l)))
这是一个从一个函数改编而来的函数,它做了类似的事情

import itertools
def nwise(iterable, n=2):
    "s -> (s0,s1), (s1,s2), (s2, s3), ... for n=2"
    iterables = itertools.tee(iterable, n)
    # advance each iterable to the appropriate starting point
    for i, thing in enumerate(iterables[1:],1):
        for _ in range(i):
            next(thing, None)
    return zip(*iterables)
供您使用:

for n in range(1, len(s)):
    print(list(nwise(s, n+1)))
import itertools
def nwise(iterable, n=2):
    "s -> (s0,s1), (s1,s2), (s2, s3), ... for n=2"
    iterables = itertools.tee(iterable, n)
    # advance each iterable to the appropriate starting point
    for i, thing in enumerate(iterables[1:],1):
        for _ in range(i):
            next(thing, None)
    return zip(*iterables)
for n in range(1, len(s)):
    print(list(nwise(s, n+1)))