2015-10-06 90 views
-3

爲什麼在下面的函數中只返回最後一項呢?函數只返回最後一項

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

print(lem(file)) 
+1

因爲你總是改變lem變量的值。將lem更改爲列表並追加行分割的結果。 –

+0

如果你只想要最後一個項目,你將如何實現它不同? –

+0

@PeterWood我認爲他的頭銜有誤導性。 –

回答

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 

在發電機的情況下,你需要循環輸出(隱含在潑濺與*或與''.join合併,或明確與for循環),打印直接返回的發電機幾乎是無用的(它將是通用generatorrepr,如<generator object lem at 0xdeadbeef>)。

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

+0

如果我想要所有的iems,它會怎麼樣? – fff

+0

以什麼格式? –