[英]Can't make created python function return a value which I can then use in another calculation
[英]I have a method / function in python in which i'm trying to get a return value which i can then use as a variable in another function
所以我正在嘗試學習 Python,同時編寫一些代碼來幫助自己完成一些平凡的任務。 所以我有一個函數,如果我使用打印語句來顯示我需要的內容,它就可以正常工作,但是當我將“打印”語句替換為“返回”時,我只得到列表中的第一個元素,我知道它是因為“返回”導致函數退出,但我不知道如何讓它返回其余元素。 我已經嘗試了很多東西,現在已經閱讀了幾個小時:(但仍然沒有進一步。目標:讀取目錄中的所有“*.common”文件,然后將它們與包含一些名稱的文本文件進行比較,如果它們match 返回 *.common 文件的名稱,因此我可以在另一個函數中將它用作變量。到目前為止我擁有的代碼
# This method gets the list of common files....
def get_common_files():
path = (config_home)
files = []
for r, d, f in os.walk(path):
for file in f:
if '.common' in file:
files.append(file)
for f in files:
return files
new_file = get_common_files()
def build_default_manifest():
for line in fileinput.FileInput(new_manifest):
for name in new_file:
if line.strip() in name:
print(name) # works as it should and displays all that i need
return name # only shows me the first element
good_name = build_default_manifest()
print(good_name)
我希望我已經提供了我需要的一切,但如果沒有,請隨時回來找我...
當你這樣做時:
for f in files:
return files
這不太對。 這里有2個問題。 首先,它所做的只是返回files
——整個過程,一次。 在return
周圍放置一個循環體並沒有真正意義。 可能你想輸入return f
,迭代結果......但這會導致第二個問題......
return
語句將在第一次遇到時運行,導致函數結束,僅此而已。 因此,僅更改返回的內容return f
仍然不起作用:它只會返回files
的第一個值。
這實際上非常接近於稱為生成器的稍微更高級的模式。 如果你用這個替換上面的:
for f in files:
yield f
那么你的功能應該可以工作。 解釋它為什么起作用並不那么容易,但是這個問題有一些很好的答案應該會有所幫助。
出於好奇,您是自己從頭開始編寫的,還是從某個地方遵循示例? 我只是有點驚訝您與生成器模式的接近程度,顯然是無意的,並且假設您之前沒有意識到它。
def build_default_manifest():
for line in fileinput.FileInput(new_manifest):
for name in new_file:
if line.strip() in name:
yield name
good_name = build_default_manifest()
for name in good_name:
print(name)
就像 Z4-tier 說的,聽起來你需要一個發電機。
您可以像平常一樣使用 good_name 中的每個元素進行函數調用。
也許我在這里遺漏了一些東西,但您的 for 循環(for r、d...)不是已經創建了名為“文件”的列表嗎? 那么,為什么不直接改變:
for f in files:
return files
到
return files
哪個應該只返回整個列表?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.