Python - 相关性:错误不支持的操作数类型 /:'generator' 和 'int'

Python - Correlation: Error unsupported operand type(s) for /: 'generator' and 'int'

我正在尝试执行 python 代码,但出现错误

unsupported operand type(s) for /: 'generator' and 'int'

代码:

def getCorrelation(user1,user2):
    ## user1 and user2 are two series
    list1=[1,2,3,4,5,6,78,9,12]
    user1=np.array(user1[i] for i in list1)

    user2=np.array(user2[i] for i in list1)


    return correlation(user1,user2)

getCorrelation(user1,user2)

看看 user1,user2 类型这可以告诉你一些事情。 使用:type(user1) 和 type(user2) 并查看输出。

您的 user 表达式生成包含生成器的数组:

In [108]: np.array(i for i in alist)                                                 
Out[108]: array(<generator object <genexpr> at 0x7f0b7bc98e60>, dtype=object)

通过正确的列表理解:

In [109]: np.array([i for i in alist])                                               
Out[109]: array([1, 2, 3, 4])

回溯应该显示错误发生在将这样的数组传递给 correlation 函数时。

In [110]: np.array(i for i in alist)/2                                               
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-110-a87b95ad6f4b> in <module>
----> 1 np.array(i for i in alist)/2

TypeError: unsupported operand type(s) for /: 'generator' and 'int'

或者测试一个简单的生成器:

In [111]: g = (i for i in alist)                                                     
In [113]: g                                                                          
Out[113]: <generator object <genexpr> at 0x7f0b7bc9b0f8>
In [114]: g/2                                                                        
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-114-f5357a50c56f> in <module>
----> 1 g/2

TypeError: unsupported operand type(s) for /: 'generator' and 'int'