我有点新来编程,我想比较两个列表中的列表,而这些列表中的浮点数可能有错误。下面一个例子: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