Home  >  Article  >  Backend Development  >  How to use the input function in python to input a list

How to use the input function in python to input a list

尚
Original
2019-07-02 14:57:0370802browse

How to use the input function in python to input a list

After Python 3.0, keyboard input uses the input function

>>> x=input
>>> 123
123

Nothing is displayed on the command line. After inputting 123, it is directly assigned to x and printed.

Just using input cannot solve most data processing. Usually the input string needs to be split. Python uses the split() function to split it

>>> x=input()
1,2,3,4
>>> xlist=x.split(",")
>>> print(xlist)
['1', '2', '3', '4']

But this is still not enough. The input is Numbers, we hope that the list is also a number, so we need to further convert

>>> 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循环,把每个字符转成int值
>>> print(xlist)
[1, 2, 3, 4]

The parameters 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]

For more Python-related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to use the input function in python to input a list. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn