Home > Article > Backend Development > How to input an array in python
Python There are many ways to input an array: use the list() function to create a list whose elements are strings separated by spaces in the input. Use the numpy.array() function to create a NumPy array whose elements are space-delimited strings from the input and converted to the specified data type (such as an integer). Use the itertools.chain.from_iterable() function to create a list of newline-delimited strings from the input. Use the ast.literal_eval() function to convert the input string directly into a list whose elements are objects of primitive type. Use the json.loads() function to load the input JSON
How to use Python to input an array
In Python , you can use several methods to input an array:
1. Use the list() function
<code class="python">my_array = list(input("输入数组元素,用空格分隔:").split())</code>
This method creates a list in which each element is A string split from user input.
2. Use the numpy.array() function (requires numpy library)
<code class="python">import numpy as np my_array = np.array(input("输入数组元素,用空格分隔:").split(), dtype=int)</code>
This method creates a NumPy array in which each element is drawn from the user input Convert the split string to the given data type (integer in this case).
3. Use the itertools.chain.from_iterable() function
<code class="python">from itertools import chain my_array = list(chain.from_iterable(input("输入数组元素,用换行符分隔:").splitlines()))</code>
This method creates a list where each element is a character split from the user input. string.
4. Use the ast.literal_eval() function
<code class="python">import ast my_array = ast.literal_eval(input("输入数组,如 [1, 2, 3]:"))</code>
This method directly converts the string entered by the user into a list, where each element is of primitive type object.
5. Use the json.loads() function
<code class="python">import json my_array = json.loads(input("输入数组,如 [\"1\", \"2\", \"3\"]:"))</code>
This method converts the JSON string entered by the user into a list, where each element is of string type object.
Choose the most appropriate method based on your specific needs.
The above is the detailed content of How to input an array in python. For more information, please follow other related articles on the PHP Chinese website!