[英]Why does Python take forever to evaluate 1**4**4**4**4?
[英]Why does appending to a list take forever?
我寫了以下代碼:
import fnmatch
ll = []
for items in src:
for file in os.listdir('/Users/swaghccc/Downloads/PulledImages/'):
if fnmatch.fnmatch(file, items.split('/')[-1]):
print file
ll.append(file)
我的src
列表包含圖像的路徑。 就像是:
/path/to/image.jpg
這些圖像是目錄PulledImages
包含的圖像的子集。
匹配圖像的打印正常。 但是,當我嘗試將這些圖像名稱放入列表ll
,它將永遠永久。
我到底在做什么錯?
追加並不需要永遠。 但是,搜索列表花費的時間越長,列表就越長。 和os.listdir()
是操作系統調用,在大目錄中運行時不可避免地會變慢。
為避免這種情況,請使用字典或集而不是列表來跟蹤要與之進行比較的名稱-並在循環外部僅構建一次該集。
# run os.listdir only once, storing results in a set for constant-time lookup
import sets
files = sets.Set(os.listdir('/Users/swaghccc/Downloads/PulledImages/'))
ll = []
for item in src:
if item.split('/')[-1] in files:
ll.append(file)
社區Wiki是因為沒有MCVE我不認為這個問題在主題准則之內; 因此,不要以代表/信用獲得該答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.