Python 3.5.1 - 将多个输入读入数组 [英] Python 3.5.1 - read multiple inputs into an array
问题描述
我正在使用 python 3.5.1 并通过 Windows 上的命令提示符运行我的文件.程序运行后传递参数;即程序根据之前生成的列表提示输入.
I'm using python 3.5.1 and running my file through command prompt on windows. The arguments are being passed after the program is run; ie the program prompts for input based on a previously generated list.
我希望在以空格分隔的同一行中读取多个数字.Python 2.X 使用 raw_input 不会有问题,但事实证明这是一个挑战.
I'm looking to read in multiple numbers on the same line separated by spaces. Python 2.X it wouldn't have been an issue with raw_input but this is proving to be a challenge.
selection = list(map(int,input("Enter items to archive (1 2 etc):").split(",")))
如果我在同一行输入两个不同的数字:
If I enter two different numbers on the same line:
输入要存档的项目(1 2 等):29 30 Traceback(最近调用最后):文件G:\Learning\Python\need_to_watch.py",第 15 行,在selection = list(map(int,input("Enter items to archive (1 2 etc):").split(","))) File "", line 129 30^ 语法错误:解析时出现意外 EOF
Enter items to archive (1 2 etc):29 30 Traceback (most recent call last): File "G:\Learning\Python\need_to_watch.py", line 15, in selection = list(map(int,input("Enter items to archive (1 2 etc):").split(","))) File "", line 1 29 30 ^ SyntaxError: unexpected EOF while parsing
我放弃了单行并尝试只在循环中进行,但我得到了不同的错误
I gave up on a single line and tried just doing it in a loop but I get a different error
data=[]
while True:
entry = int(input('Item number : '))
data.append(entry)
if entry == 'q':
break
即使我没有 eval() 任何东西,它也会尝试将 'q' 评估为一个变量.
It tries to evaluate 'q' as a variable even though I haven't eval()'d anything.
这个问题说只使用 input().split() 但看起来这不再有效....接受多个用户输入在python中用空格分隔并将它们附加到列表中
This question says to just use input().split() but it would appear that this no longer works.... accepting multiple user inputs separated by a space in python and append them to a list
我可以尝试捕获 EOF 异常,但这似乎不是正确的方法,也没有必要.
I could try and catch the EOF exception, but that doesn't seem like the right way to do it, nor should it be necessary.
推荐答案
entry = input('Enter items: ')
entry = entry.split(' ')
entry = list(map(int, entry))
print(entry)
或者更简洁:
entry = list(map(int, input('Enter items: ').split(' ')))
print(entry)
这篇关于Python 3.5.1 - 将多个输入读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!