我想根据for循环增加字符串中Izip
的项数。你知道吗
例如,这是代码
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。你知道吗
是一个list comprehension,它创建了
s
片的列表。它为
n=2
创建列表[s[0:], s[1:], s[2:]]
。它可以写为常规for循环:
使用解决方案中使用的常规for循环将是:
下面是一个改编自itertools recipe的函数,它做了类似的事情。你知道吗
供您使用:
相关问题 更多 >
编程相关推荐