使用 numpy 数组输出列表中的第 n 个值

Using numpy array to output the nth value in a list

下面是一个使用 numpy 和 reduce 函数查找 3 个列表 MNDW_drawdown, PRC_overall_prec, TTS_Total_Trades 中的公共数字的函数。但是输出是 numpy 数组的形式,有什么办法可以将它转换成列表形式。我想使用 reduced 打印列表中的第 n 个值,所以它将是 list_[reduced].
代码:

from functools import reduce
import numpy as np

list_ = [ 5268, 6760,  6761 ... 15149, 15150, 15151]
def intersect(l1, l2, l3) :#function
    reduced = reduce(np.intersect1d, (l1, l2, l3))
    print(reduced)  
intersect(MNDW_drawdown, PRC_overall_prec, TTS_Total_Trades) #calling function

减少输出:

[11858 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870
 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559]

问题的答案是reduced.tolist()

您可以按照其他答案中的建议使用 .tolist() 函数。另一种方法是一开始就不使用numpy,而是使用内置的set类型,它提供了.intersection方法。将第一个列表转换为 set,然后将 .intersection 方法链接到其余参数。但是,结果也将是 set,因此无论如何您都必须转换为列表。

def intersect(a: list, b: list, c: list) -> list:
    return list(set(a).intersection(b).intersection(c))

注意结果不会排序。