Home > Article > Backend Development > 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)
The execution result is as follows:
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!