簡體   English   中英

Python - 從函數返回值

[英]Python - Return values from a function

我有這個配置文件:

[test]
one: value1
two: value2

此函數返回項目,來自配置文件的section test的值,但是當我調用該函數時,只返回第一項(one,value1)。

def getItemsAvailable(section):
    for (item, value) in config.items(section):
        return (item, value)

我用這個函數調用getItemsAvailable():

def test():
    item, value = getItemsAvailable('test')
    print (item, value)

我想我應該在getItemsAvailable()函數上創建一個列表,並返回列表以讀取test()函數的值,是嗎?

有什么建議?

謝謝!!

使用列表理解。 更改

for (item, value) in config.items(section):
    # the function returns at the end of the 1st iteration
    # hence you get only 1 tuple. 
    # You may also consider using a generator & 'yield'ing the tuples
    return (item, value) 

return [(item, value) for item, value in config.items(section)]

關於你的test()函數:

def test():
    aList = getItemsAvailable('test')
    print (aList)

使用生成器功能:

def getItemsAvailable(section):
    for (item, value) in config.items(section):
        yield (item, value)

得到這樣的項目:

def test():
    for item, value in getItemsAvailable('test'):
        print (item, value)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM