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

How to enter an array from the keyboard in Python

下次还敢
Release: 2024-05-05 19:51:48
Original
1245 people have browsed it

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>
Copy after login
  1. Useinput() Get the user's input:
<code class="python">user_input = input("请输入数组元素,用逗号分隔:")</code>
Copy after login
  1. Convert the string entered by the user into a list:
<code class="python">user_list = user_input.split(',')</code>
Copy after login
  1. Usenumpy.array() Convert list to NumPy array:
<code class="python">array = np.array(user_list, dtype=int)</code>
Copy after login

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>
Copy after login

Output:

<code>[1 2 3 4 5]</code>
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template