Python-相关性:/:“生成器”和“ INT”的错误操作数类型不受支持

时间:2019-04-29 15:28:43

标签: python scipy correlation recommendation-engine

我正在尝试执行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)

2 个答案:

答案 0 :(得分:1)

您的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'

答案 1 :(得分:-1)

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