[英]python generator of dynamic length
我有这个:
def get_set(line, n=3):
words = line.split()
for i in range(len(words) - n):
yield (words[i], words[i+1], words[i+2])
for i in get_set('This is a test'):
print(i)
但是,正如您在yield
调用中看到的那样,它经过硬编码才能与3一起工作。如何重写yield
行以与通过n
kwarg传递的任何数字一起工作?
(代码生成器在一个句子中每三个连续单词的集合,希望它生成我作为n
传递的所有内容)
您总是可以将元组超出范围
def get_set(line, n=3):
words = line.split()
for i in range(len(words) - (n-1)):
yield tuple(words[i:i+n])
请注意,您需要在len(words) - (n-1)
而不是len(words)-n
len(words) - (n-1)
范围内进行迭代,以获取所有连续对。
用
for i in get_set('This is a very long test'):
print(i)
这给出:
n = 3:
('This', 'is', 'a') ('is', 'a', 'very') ('a', 'very', 'long') ('very', 'long', 'test')
n = 4:
('This', 'is', 'a', 'very') ('is', 'a', 'very', 'long') ('a', 'very', 'long', 'test')
for row in zip(*[words[x:] for x in range(n)]):
yield row
我认为应该工作
for i in range(len(words)-n):
yield words[i:i+n]
也应该工作...
(如果需要,可以投射到元组中……)
您可以在列表上使用切片 :
def get_set(line, n=3):
words = line.split()
for i in range(0, len(words), n):
yield words[i:i+n]
for i in get_set('This is a test'):
print(i)
['This', 'is', 'a']
['test']
for i in get_set('This is another very boring test', n=2):
print(i)
['This', 'is']
['another', 'very']
['boring', 'test']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.