How to use input to input a list in Python

angryTom
Release: 2020-02-07 09:49:29
Original
21495 people have browsed it

How to use input to input a list in Python

How to use input to input a list in Python

When using input to input data, use commas to separate each item in the list, and then use ast.literal_eval()The method can be converted into a list.

The code is as follows:

import ast
lists = ast.literal_eval(input("请输入列表,使用逗号隔开: "))  
print(lists)
Copy after login

The execution result is as follows:

How to use input to input a list in Python

The function of ast.literal_eval() is torestore the data to It itself or a data type that can be converted into . The

eval() function also has the same effect, but they are different:

eval does not know whether the content to be converted is legal before doing the calculation. (safe) python data type. It is only calculated when the function is called. If the calculated content is not a legal Python type, an exception will be thrown.

ast.literal will determine whether the content to be calculated is a legal python type after calculation. If so, the operation will be performed, otherwise the operation will not be performed.

Therefore, it is recommended to use ast.literal_eval

Many python training videos, all on the python learning network, welcome to learn online!

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!