Home  >  Article  >  Backend Development  >  How to enter an array from the keyboard in Python

How to enter an array from the keyboard in Python

下次还敢
下次还敢Original
2024-05-05 19:51:481185browse

Get user keyboard input through the input() function, use split(',') to separate the input into a list by commas, and finally use np.array() to convert the list into a NumPy array.

How to enter an array from the keyboard in Python

Using Python to input an array from the keyboard

How to use Python to input an array from the keyboard?

Using Python's input() function, you can get an array of user input from the keyboard.

Detailed steps:

  1. Import numpy Library:
<code class="python">import numpy as np</code>
  1. Useinput() Get the user's input:
<code class="python">user_input = input("请输入数组元素,用逗号分隔:")</code>
  1. Convert the string entered by the user into a list:
<code class="python">user_list = user_input.split(',')</code>
  1. Usenumpy.array() Convert list to NumPy array:
<code class="python">array = np.array(user_list, dtype=int)</code>

Sample code:

<code class="python">import numpy as np

user_input = input("请输入数组元素,用逗号分隔:")
user_list = user_input.split(',')
array = np.array(user_list, dtype=int)

print(array)</code>

Output:

<code>[1 2 3 4 5]</code>

The above is the detailed content of How to enter an array from the keyboard in Python. 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