函数仅返回最后一项

时间:2015-10-06 12:40:39

标签: python python-3.x

为什么在以下函数中它只返回最后一项?

def lem(file):
    lem = ''
    for line in file:
        lem = line.split()[1]
    return lem

print(lem(file))

2 个答案:

答案 0 :(得分:2)

在每次迭代中,您重新分配lem的值。 您需要在每次迭代之前将其保存到列表中(例如)。

def lem(myfile):
    res = []
    for line in myfile:
        res.append(line.split()[1])
    return ' '.join(res) # joining to string

print(lem(myfile))

停止使用内置名称,例如file

答案 1 :(得分:2)

因为您只返回了一件事(每次都重新创建lem)。如果您想要返回多个内容,请连接字符串,返回列表或将其设为generator function

# Concatenating
def lem(file):
    lem = []
    for line in file:
        lem.append(line.split()[1])
    return ''.join(lem)
    # Returning a list is the same, just omit the ''.join()
# To use when using ''.join, just print the return value
print(lem(file))
# To use when returning a list, loop (as in the generator case below), or print the list itself as in the ''.join case and it will print the list's repr

# Generator
def lem(file):
    for line in file:
        yield line.split()[1]
# To use the generator, either loop and print:
for x in lem(file):
    print(x)
# Or splat the result generator to print if you're using Py3's print
# function (or using from __future__ import print_function on Py2)
print(*lem(file)) # Separates outputs with spaces; sep="\n" to put them on separate lines, sep="" to print them back-to-back, etc.
# Or to print (or assign) them all at once as a single string:
print(''.join(lem(file))) # Change '' to whatever string you want to put between all the outputs

在生成器的情况下,你需要循环输出(隐式地用sp {*或与''.join结合,或明确地用for循环),打印生成器直接返回主要是无用的(它将是repr的{​​{1}},类似于generator