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

时间:2019-05-19 04:32:39

标签: python for-loop functional-programming

我想压缩循环确定的语句数。

例如,这是代码

 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个可迭代项。

我不太确定如何正确添加到代码语句中(即zip语句中具有正确的可迭代数)

1 个答案:

答案 0 :(得分:1)

>>> s = '123456'
>>>
>>> for n in range(1, len(s)):
    print(list(zip(*[s[i:] for i in range(0,n+1)])))

[('1', '2'), ('2', '3'), ('3', '4'), ('4', '5'), ('5', '6')]
[('1', '2', '3'), ('2', '3', '4'), ('3', '4', '5'), ('4', '5', '6')]
[('1', '2', '3', '4'), ('2', '3', '4', '5'), ('3', '4', '5', '6')]
[('1', '2', '3', '4', '5'), ('2', '3', '4', '5', '6')]
[('1', '2', '3', '4', '5', '6')]

[s[i:] for i in range(0,n+1)]

是一个list comprehension,可创建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)))

这是从itertools recipe改编而成的函数,其功能类似。

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)))