[英]Is max() of a generator building a list-like object or is it working more efficient?
假設我有一個目錄,其中包含名稱為'filename_1'
、 'filename_2'
等'filename_2'
,並且有一個用於查找最新編號的生成器models_paths
:
mypath = 'my/path/filename'
models_paths = Path(mypath).parent.glob(Path(mypath).name + '*')
number_newest = max(int(str(file_path).split('_')[-1]) for file_path in models_paths)
我想知道max
是否正在構建類似列表的數據結構,或者它是否正在使用類似的算法
number_newest = None
for file_path in models_paths:
number_current = int(str(file_path).split('_')[-1])
number_newest = number_current if number_newest is None else max(number_current, number_newest)
換句話說:如果我寫,我會失去處理效率和/或內存效率嗎?
mypath = 'my/path/filename'
models_paths = Path(mypath).parent.glob(Path(mypath).name + '*')
models_paths = list(models_paths)
number_newest = max(int(str(file_path).split('_')[-1]) for file_path in models_paths)
?
max
不構建列表。
在此示例中,可以使用自定義對象清楚地證明這一點:
class Thing:
def __init__(self, x):
self.x = x
print(f'creating {x}')
def __lt__(self, other):
return self.x < other.x
def __del__(self):
print(f'destroying {self.x}')
def __str__(self):
return f'<{self.x}>'
print(max(Thing(i) for i in range(5)))
這使:
creating 0
creating 1
destroying 0
creating 2
destroying 1
creating 3
destroying 2
creating 4
destroying 3
<4>
destroying 4
如您所見,一旦確定它不再是具有最大值的對象,就會在每個對象上調用__del__
方法。 如果將它們附加到列表中,則情況並非如此。
對比:
print(max([Thing(i) for i in range(5)]))
這使:
creating 0
creating 1
creating 2
creating 3
creating 4
destroying 3
destroying 2
destroying 1
destroying 0
<4>
destroying 4
您可以編寫一個(效率較低的)等效函數並證明它執行相同的操作:
def mymax(things):
empty = True
for thing in things:
if empty or (thing > maximum): # parentheses for clarity only
maximum = thing
empty = False
if empty:
raise ValueError
return maximum
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.