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

Sample code:

import numpy as np

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

print(array)
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:
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