How to input the number of input in python

2020-05-03 12:00发布

I want to input in inline

1. input number : 5  
2. 1 5 3 4 2

how to receive input for the number of inputs in python?

I've been tried like this:

num=int(input("inputs_num"))
mlist=[]
for i in range(num):
    n=int(input())
    mlist.append(n)
print(mlist)

I want to input in inline

标签: python
2条回答
狗以群分
2楼-- · 2020-05-03 12:23

simple

i = list(map(int, input("Numbers: ").split()))
print(i)

It will accept multiple integers as input on a single line in Python3

查看更多
Lonely孤独者°
3楼-- · 2020-05-03 12:24

You want to first get the whole line as a string, then split by spaces into a list, then convert each element into int.

So, the flow would look something like:

"1 5 3 4 2" -> Split -> ['1', '5', '3', '4', '2'] -> Map -> [1, 5, 3, 4, 2]
num=int(input("inputs_num"))
mstr = input().split() # ['1', '5', '3', '4', '2']
mlist=[]
for el in mstr:
  mlist.append(int(el))

Or a more pythonic way would be:

  1. Using list comprehension
num=int(input("inputs_num"))
mlist=[int(i) for i in input().split()]
  1. Using map
num=int(input("inputs_num"))
mlist=list(map(int, input().split()))
查看更多
登录 后发表回答