我有點新來編程,我想比較兩個列表中的列表,而這些列表中的浮點數可能有錯誤。下面一個例子:Python - 列表與近似浮點數的列表比較
first_list = [['ATOM', 'N', 'SER', -1.081, -16.465, 17.224],
['ATOM', 'C', 'SER', 2.805, -3.504, 6.222],
['ATOM', 'O', 'SER', -17.749, 16.241, -1.333]]
secnd_list = [['ATOM', 'N', 'SER', -1.082, -16.465, 17.227],
['ATOM', 'C', 'SER', 2.142, -3.914, 6.222],
['ATOM', 'O', 'SER', -17.541, -16.241, -1.334]]
預期輸出:
Differences = ['ATOM', 'C', 'SER', 2.805, -3.504, 6.222]
到目前爲止,我tryings:
def aprox (x, y):
if x == float and y == float:
delta = 0.2 >= abs(x - y)
return delta
else: rest = x, y
return rest
def compare (data1, data2):
diff = [x for x,y in first_list if x not in secnd_list and aprox(x,y)] + [x for x,y in secnd_list if x not in first_list and aprox(x,y)]
return diff
或者與元組的幫助,但我不知道如何在建立近似值:
def compare (data1, data2):
first_set = set(map(tuple, data1))
secnd_set = set(map(tuple, data2))
diff = first_set.symmetric_difference(secnd_set)
return diff
希望你能幫助我! :)
您最初的'compare'函數的參數'data1'和'data2',但你引用(全球?)對象'first_list'和'secnd_list'從不使用的參數。 – blacksite
試試這個http://stackoverflow.com/questions/6105777/how-to-compare-a-list-of-lists-sets-in-python – manvi77
fyi'isinstance(x,float)'是你應該如何檢查數字鍵入 – ryugie