为什么在函数中生成一个项目与打印该项目给出不同的输出?

Why does yielding an item in a function give different output than printing the item?

我编写此函数是为了读取表示数字的单词列表,并将 1-9 位数字与乘数配对。

def listpairs(element):
    pair = []
    for word in enumerate(element):
        pair.append(word[1])
        if word[1] in denoms:
            yield pair
            pair.clear()
        if word[1] in digits and word[0] == (len(element)-1):
            yield pair

当我用测试字符串尝试时,它给出了这个:

list(listpairs('two hundred three ten four'.split())
[['four'], ['four'], ['four']]

如果我用 print(pair) 替换 yield,它会给出预期的输出:

['two', 'hundred']
['three', 'ten']
['four']

为什么会这样? yield 是不是用错工具了?

解决方案

您一直在生成相同的列表。替换:

pair.clear()

与:

pair = []

获取新列表。

示例:

from string import digits
denoms = ['hundred', 'ten']

def listpairs(element):
    pair = []
    for word in enumerate(element):
        pair.append(word[1])
        if word[1] in denoms:
            yield pair
            pair.clear()
        if word[1] in digits and word[0] == (len(element)-1):
            yield pair

list(listpairs('two hundred three ten four'.split()))

给出:

[['four'], ['four']]

但是:

from string import digits

denoms = ['hundred', 'ten']

​

def listpairs(element):
    pair = []
    for word in enumerate(element):
        pair.append(word[1])
        if word[1] in denoms:
            yield pair
            pair = []
        if word[1] in digits and word[0] == (len(element)-1):
            yield pair


list(listpairs('two hundred three ten four'.split()))

结果整数:

[['two', 'hundred'], ['three', 'ten']]

说明

虽然 mylist.clear() 删除了列表中的所有内容,但它仍然是同一个列表。产生相同的列表会导致在输出中多次出现相同的列表。 另一方面,赋值 mylist = [] 创建一个新列表,重用名称 mylist。在这里重用这个名字很好,因为你产生了列表,即它会在函数之外。