PYTHON3 python我的解释器告诉我有numpy,但是当我执行我的整个代码时,打印错误消息

时间:2019-03-17 16:43:19

标签: python-3.x

>>> import numpy
>>> numpy.std(arr)
1.4142135623730951
>>>

我的口译员打印正确答案 但是我的整个代码

import numpy

def addarr(N,K,score):
    arr=[]
    a=10000
    this = int(N)-int(K)+1

    for j in range(0,this):
        for i in range(j,j+int(K)):
            arr.append(score[i])
            print(i)
        print("asdfasdfasdfasfasdf")
        print(arr)
        b = numpy.std(arr)

        if a>b:
            a=b
    return a

if __name__ == "__main__":
    NandK = input()
    N, K = NandK.split()

    string = input()
    score =[]
    score = string.split()
    print(score)

    print(len(score))
    answer = addarr(N,K,score)
    print(answer)


我的整个代码显示有关numpy的错误消息

   b = numpy.std(arr)
['1', '2', '3']
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 3242, in std
    **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/core/_methods.py", line 140, in _std
    keepdims=keepdims)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/core/_methods.py", line 107, in _var
    arrmean = umr_sum(arr, axis, dtype, keepdims=True)
TypeError: cannot perform reduce with flexible type

我该如何解决。 我已经用pip3安装了“ numpy”

我使用的是python3,我的版本是3.7

我一直尝试将numpy导入为np,但是它也不起作用。

这是我的输入

5 3
1 2 3 4 5

1 个答案:

答案 0 :(得分:0)

有两种解决方法。

一种是将arr.append(score[i])更改为arr.append(int(score[i]))

另一种方法是在以下代码中取消注释此行# arr=[int(x) for x in arr]

import numpy

def addarr(N,K,score):
    arr=[]
    a=10000
    this = int(N)-int(K)+1

    for j in range(0,this):
        for i in range(j,j+int(K)):
            arr.append(int(score[i]))
            print(i)
        print("asdfasdfasdfasfasdf")
        print(arr)
        # The next line can trun ['1', '2', '3'] to [1,2,3]
        # arr=[int(x) for x in arr]
        b = numpy.std(arr)
        print('b=',b)
        if a>b:
            a=b
    return a

if __name__ == "__main__":
    NandK = input()
    N, K = NandK.split()

    string = input()
    score =[]
    score = string.split()
    print(score)

    print(len(score))
    answer = addarr(N,K,score)
    print(answer)