Python:raw_input的奇怪行为

时间:2016-04-11 15:28:43

标签: python python-2.7 raw-input

使用raw_input时,下面的代码提供了一个意外的答案。任何人都可以解释我发生了什么以及如何解决它?

import numpy as np
response = raw_input("What is your move? ")
response=np.array(response)
changingPositions=np.flatnonzero(response)
print changingPositions

response=np.array([0,1,0])
changingPositions=np.flatnonzero(response)
print changingPositions

执行是:

What is your move? [0,1,0]
[0]
[1]

预期答案是

[1]

2 个答案:

答案 0 :(得分:2)

raw_input返回一个字符串,实际上np.flatnonzero(np.array('adfsgh'))也会生成array([0])。所以只需列出一下整数:

In [1]: import numpy as np

In [2]: response = raw_input("What is your move? ")
What is your move? 0,1,0

In [3]: positions = np.array(map(int, response.split(',')))

In [4]: changing_positions = np.flatnonzero(positions)

In [5]: changing_positions
Out[5]: array([1])

答案 1 :(得分:1)

响应是字符串元素。但是你想要一个列表

因此您需要将用户输入解析为列表。您应该使用input()而不是raw_input()来解析用户输入,或使用eval(raw_input())eval()将字符串解析为元素...

但是我建议用try..except包围这个函数,检查用户输入是否有效,如果输入仍然无效,还要循环:

import numpy as np

isValid = False

while !isValid:
    try:
        response = input("What is your move? ")
        isValid = True
    except:
        print("Input is not valid!!")

response=np.array(response)
changingPositions=np.flatnonzero(response)
print changingPositions

response=np.array([0,1,0])
changingPositions=np.flatnonzero(response)
print changingPositions