动态长度为

时间:2015-08-06 18:25:12

标签: python

我有这个:

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

3 个答案:

答案 0 :(得分:1)

你总是可以在范围之外制作一个元组

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中进行迭代才能获得所有连续对。

使用

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

答案 1 :(得分:0)

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]

也应该有用......

(如果需要,转换为元组......)

答案 2 :(得分:0)

您可以在列表中使用切片

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']