2015-11-08 767 views
0

我有一個腳本,它接收文件中的列並將它們放入列表中,找到列表中的最小值和最大值並將其減去,這裏是代碼的一部分這樣的:如何在python中處理列表中的空集

for line in f: 
    new_n = float(line) 
    temp.append(new_n) 
min_ = min(temp) 
max_ = max(temp) 
tot = (max_ - min_) 

一些文件有全0的名單,我得到的錯誤:ValueError: min() arg is an empty sequence如何處理這些空集,返回0,如果整個列表中有0

我猜是這樣:

for num in temp: 
    if num == 0: 
     tot = 0 
    else: 
     min_ = min(temp) 
     max_ = max(temp) 
     tot = (max_ - min_) 

回答

0

全0的文件沒有給出錯誤...它沒有數據的文件是令人不安的。

此錯誤發生

ValueError: min() arg is an empty sequence 

當參數到MIN FUNC是空的列表(或元組)。執行min(temp)時,您的臨時列表爲空。

0

就像@Jug提到的那樣,文件中有空行導致了這個問題。在調用min或max之前,您應該忽略空行或檢查空列表:

if temp: 
    min_ = min(temp) 
    max_ = max(temp) 
    tot = (max_ - min_)