首页 > 解决方案 > 如何在函数输出中获取唯一值列表

问题描述

假设我有这样的功能:

def function(a,b):
    for x in np.nditer(a):
        dAB = x-b
        pred = np.ceil([dAB+b*2])
        print(pred)

array1 = np.array([1,2,3,4,5])
array2 = np.array([4,5,6,7,8])

我的输出是:

function(array1,array2)

[[5. 6. 7. 8. 9.]]
[[ 6.  7.  8.  9. 10.]]
[[ 7.  8.  9. 10. 11.]]
[[ 8.  9. 10. 11. 12.]]
[[ 9. 10. 11. 12. 13.]]

我将如何获得如下输出:

function(array1,array2)

array([5,6,7,8,9,10,11,12,13])

我想要的是跨数组获取所有唯一值并将其放入一个数组中。

标签: pythonnumpy

解决方案


只需使用set

import numpy as np

def function(a,b):
    res = set()
    for x in np.nditer(a):
        dAB = x-b
        pred = np.ceil(dAB+b*2)
        res.update(pred)
    return np.array(res)

前任。

>>> array1 = np.array([1,2,3,4,5])
>>> array2 = np.array([4,5,6,7,8])

>>> print(function(array1,array2))
{5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0}

推荐阅读