我正在嘗試創建一個小程式,用于搜索影像檔案夾,選擇一個,檢查其大小并在所選影像至少為 5KB 時完成。如果不是,那么我需要它回圈回到選擇步驟(然后檢查尺寸,等等..)
我正在使用函式進行選擇和大小檢查,但是當我嘗試在 while 回圈中使用它們時,我遇到了各種縮進錯誤,現在我很困惑。我已經評論了我使用該函式的部分,但實際上我想我希望整個事情回圈回頂部的評論..這是我的代碼 -
#CHOOSE POINT
def chosen():
random.choice(os.listdir(r"/Users/me/p1/images"))
def size():
os.path.getsize(r"/Users/me/p1/images/" chosen)
thresh = 5000
while size < thresh:
print(chosen " is too small")
# loop back to CHOOSE POINT
else:
print(chosen " is at least 5KB")
我想這一切都錯了嗎?在我的 while 回圈中使用該函式會做我想要的嗎?實作我想要做的事情的最佳方法是什么?我對此很陌生,并且非常困惑。
uj5u.com熱心網友回復:
首先要意識到的是這樣的代碼:
def chosen():
random.choice(os.listdir(r"/Users/me/p1/images"))
只是一個函式的定義。它僅在您每次實際呼叫它時運行,使用chosen().
其次,random.choice()將從提供的串列中隨機選擇一個(盡管每次呼叫它時都從磁盤中讀取它的效率相當低,并且不清楚為什么你會隨機選擇一個,但這沒關系),但是因為你沒有' t 實際上return是值,函式不是很有用。做出選擇,然后丟棄。相反,您可能想要:
def chosen():
return random.choice(os.listdir(r"/Users/me/p1/images"))
三、這個函式定義:
def size():
os.path.getsize(r"/Users/me/p1/images/" chosen)
它嘗試使用chosen,但這只是您之前定義的函式的名稱。您可能想要獲取所選實際檔案的大小,該函式需要將其作為引數提供:
def size(fn):
return os.path.getsize(r"/Users/me/p1/images/" fn)
現在使用這些功能:
file_size = 0
threshold = 5000
while file_size < threshold:
a_file = chosen()
file_size = size(a_file)
if file_size < threshold:
print(a_file " is too small")
else:
print(a_file " is at least 5KB")
print('Done')
變數file_size被初始化為 0,以確保回圈開始。回圈將繼續進行,直到開始時滿足條件。
每次chosen()執行時,回傳的值都被記住為變數a_file,然后您可以在其余代碼中使用它來參考。
然后將其傳遞給size(),以獲得大小,最后執行測驗以列印正確的訊息。
實作相同目標的更有效方法:
threshold = 5000
while True:
a_file = chosen()
file_size = size(a_file)
if file_size < threshold:
print(a_file " is too small")
else:
break
print(a_file " is at least 5KB")
在break剛剛退出while這將繼續下去,永遠,因為它測驗回圈True。這樣可以避免對同一事物進行兩次測驗。
所以,你最終會得到:
import random
import os
def chosen():
return random.choice(os.listdir(r"/Users/me/p1/images/"))
def size(fn):
return os.path.getsize(r"/Users/me/p1/images/" fn)
threshold = 5000
while True:
a_file = chosen()
file_size = size(a_file)
if file_size < threshold:
print(a_file " is too small")
else:
break
print(a_file " is at least 5KB")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/366289.html
