How to input a list into the python input function

created at 07-01-2021 views: 2

description

After Python3.0, keyboard input uses the input function:

>>> x=input
>>> 123
123

Nothing is displayed on the command line. After entering 123, assign it directly to x and print it.

It is not possible to solve most of the data processing by just using input. Usually the input string needs to be split. Python uses the split() function to split.

>>> x=input()
1,2,3,4

>>> xlist=x.split(",")
>>> print(xlist)

['1', '2', '3', '4']

solution

But this is still not enough. The input is a number, and we hope the list is also a number, so further conversion is needed.

>>> x=input()

1,2,3,4

>>> xlist=x.split(",")
>>> print(xlist)

['1', '2', '3', '4']
>>> xlist = [int(xlist[i]) for i in range(len(xlist))] #for loop, convert each character to int value

>>> print(xlist)

[1, 2, 3, 4]

The parameter of the split() function can be any separator, including (a,b,c….;1,2,3…;%,!,*,space)

>>> x=input()

1 2 3 4

>>> xlist=x.split(" ")
>>> print(xlist)

['1', '2', '3', '4']

>>> xlist = [int(xlist[i]) for i in range(len(xlist))]
>>> print(xlist)

[1, 2, 3, 4]
Please log in to leave a comment.