如何在输入的多行中以n个数字作为输入

时间:2019-07-25 11:28:22

标签: python-3.x list

我想使用n个数字作为输入,然后在用户之前输入n时具有多行输入。

我的代码在这里:

num=int(input)

for i in range(0,2)    
    for x in range(0,num)

例如,我需要从用户输入中取n来知道我必须走多少行。每行我有2个原始元素。这里用户输入的n为3,所以我们有3行输入,每行有2个元素。例如:n = 3第一行= [1,10]第二行= [7,3]第三行= [5,2]

3 个答案:

答案 0 :(得分:0)

如果我理解这一权利,我认为这是您正在寻找的解决方案。

num=input("Please specify how many inputs you want to take in: ")
arr = []

print("Prompting for "+str(num)+" inputs:")
for i in range(0,int(num)):
    arr.append(input(str(i+1)+": "))

print("Inputs as indexes in array are:")
count=0
for k in arr:
    print(str(count)+": "+str(k))
    count=count+1

这个想法是提示用户输入一定数量的输入并循环遍历该次数,每次都将额外的输入添加到数组中。如果我理解正确,那么以后可以访问该数组,就好像它是多行一样。

答案 1 :(得分:0)

我认为您有一些这样的数据

1
a b c ...
2
d e f ...
3
g h i ...
...
...
...
n

你不知道n

尝试一下:

while True:
    try:
        for i in range(x):
            # do something
    except EOFError:
        break

您从标准输入读取了输入,并且当“输入用完”时,python会抛出EOFErrorEOF是文件结尾。它的基本含义是没有更多的输入可取。当您收到此错误时(except子句就是这样做的),您就会跳出循环。

阅读评论后进行编辑

n = int(input())
for i in range(n):
    a, b = map(int, input().split())

答案 2 :(得分:0)

您想读取数字,Python为您提供了一个函数input,它可以读取 strings ,因此,您要做的第一件事是编写一个读取字符串并返回数字的函数

def intinput(prompt, n_of_trials=1):
    ntry = 0
    while True:
        n = input(prompt)
        ntry:
            return int(n)
        except ValueError:
            ntry +=1
            if ntry <= n_of_trials:
                print('Error converting "%s" to an integer, please try again'%n)
            else:
                raise ValueError

其中n_of_trials(默认参数)是在不正常失败之前将恢复多少错误。

使用此功能后,如果我能正确理解您的要求,则可以按以下方式组织您的代码

n = intinput('How many numbers are you going to input? ', 2)
list_of_numbers = [intinput('please input no. %d/%d: '%(i+1,n)) for i in range(n)]

示例运行:

In [18]:     n = intinput('How many numbers are you going to input? ', 2)
    ...:     list_of_numbers = [intinput('please input no. %d/%d: '%(i+1,n)) for i in range(n)]
How many numbers are you going to input? 4
please input no. 1/4: 1
please input no. 2/4: 2
please input no. 3/4: 3
please input no. 4/4: 4

In [19]: print(list_of_numbers)
[1, 2, 3, 4]

In [20]:     n = intinput('How many numbers are you going to input? ', 2)
    ...:     list_of_numbers = [intinput('please input no. %d/%d: '%(i+1,n)) for i in range(n)]
How many numbers are you going to input? 4
please input no. 1/4: pip
Error converting "pip" to an integer, please try again
please input no. 1/4: 1
please input no. 2/4: pep
Error converting "pep" to an integer, please try again
please input no. 2/4: 2
please input no. 3/4: pop
Error converting "pop" to an integer, please try again
please input no. 3/4: 55
please input no. 4/4: 11

In [21]: print(list_of_numbers)
[1, 2, 55, 11]