python : find difference between two arrays in python

标签 python python-2.7

我在 python 中有两个数组。

arr1 = [(7, 0.78, 7920), (8, 0.9, 9000)]
arr2 = [(7, 1.68, 8460)]

在此数组中,第一个值是 ID (7,8,7)。我希望结果基于 ID。如果 ID 相同则获取其他两个值之间的差异。
arr1arr2 ID 7 相同则减去 (1.68-0.78 = 0.9) 和 (8460-7920 = 540) 否则将相同。 如何获得这样的结果?

diffArray = [(7, 0.9, 540), (8, 0.9, 9000)]

最佳答案

这是一种方法。首先,我正在创建从 ID 到其他值的字典:

arr1 = [(7, 0.78, 7920), (8, 0.9, 9000)]
arr2 = [(7, 1.68, 8460)]

dict1 = {i: (x, y) for i, x, y in arr1}
dict2 = {i: (x, y) for i, x, y in arr2}

然后我使用带有条件的列表理解来做正确的事情:

diffArray = [
    (
        i,
        abs(dict2[i][0] - dict1[i][0]),
        abs(dict2[i][1] - dict1[i][1]),
    )
    if i in dict2
    else (i, dict1[i][0], dict1[i][1])
    for i in dict1
]

结果可能有点出乎意料:

[(7, 0.8999999999999999, 540), (8, 0.9, 9000)]

明显的不精确是由于浮点表示。要解决这个问题(如果它很重要),请使用 Decimal 或对值进行四舍五入。

关于 python : find difference between two arrays in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49668991/

相关文章:

python - 在 Pandas 中重采样和归一化不规则时间序列数据

python-2.7 - 从 Pandas 数据帧保存没有双引号的csv文件

python - 虚拟环境中的 Opencv3 和 Python 2.7 - AttributeError : 'module' object has no attribute 'createLBPHFaceRecognizer'

python - Python 中的深度学习 - 随机梯度下降 - 分解代码

python - 有没有办法使用 atexit 运行异步协程?

python - heapify的O(n)算法

python - virtualenv : ERROR - Failed to load fernet while encrypting value 上的 apache Airflow

python - 在排序数据上拟合回归模型

python - 尝试从函数创建对象属性

python - 在python中下载rss内容