[英]python generator of dynamic length
I have this: 我有这个:
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)
But as you can see in the yield
call, it's hard-coded to work with 3. How can I rewrite the yield
line to work with whatever number is passed via the n
kwarg? 但是,正如您在
yield
调用中看到的那样,它经过硬编码才能与3一起工作。如何重写yield
行以与通过n
kwarg传递的任何数字一起工作?
(the code generators sets of each three consecutive words in a sentence, want it to generate whatever I pass as n
) (代码生成器在一个句子中每三个连续单词的集合,希望它生成我作为
n
传递的所有内容)
You could always just make a tuple out of the range 您总是可以将元组超出范围
def get_set(line, n=3):
words = line.split()
for i in range(len(words) - (n-1)):
yield tuple(words[i:i+n])
Note you need to iterate in range len(words) - (n-1)
not len(words)-n
to get all consecutive pairs. 请注意,您需要在
len(words) - (n-1)
而不是len(words)-n
len(words) - (n-1)
范围内进行迭代,以获取所有连续对。
With 用
for i in get_set('This is a very long test'):
print(i)
This gives: 这给出:
n=3: n = 3:
('This', 'is', 'a') ('is', 'a', 'very') ('a', 'very', 'long') ('very', 'long', 'test')
n=4: 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
should work I think 我认为应该工作
for i in range(len(words)-n):
yield words[i:i+n]
should also work ... 也应该工作...
(cast to tuple if needed ...) (如果需要,可以投射到元组中……)
You can use slicing on the list: 您可以在列表上使用切片 :
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.