Home > Backend Development > Python Tutorial > How to input an array in python

How to input an array in python

藏色散人
Release: 2019-08-07 13:49:58
Original
51759 people have browsed it

How to input an array in python

How to input an array in python?

Python input array

One-dimensional array:

arr = input("")    //输入一个一维数组,每个数之间使空格隔开
num = [int(n) for n in arr.split()]    //将输入每个数以空格键隔开做成数组
print(num)        //打印数组
Copy after login

One-dimensional array input and output example:

How to input an array in python

Recommended: [Python Tutorial]

Two-dimensional array:

(with n *n two-dimensional array as an example)

n = int(input())        //输入二维数组的行数和列数
line = [[0]*n]*n        //初始化二维数组
for i in range(n):
    line[i] = input().split(" ")       //输入二维数组,同行数字用空格分隔,不同行则用回车换行
print(line)            //打印二维数组
Copy after login

Two-dimensional array printing example:

How to input an array in python

If the elements in the two-dimensional array are all integers, you can Add:

line[i] = [int(j) for j in line[i]]
Copy after login

i.e. enter:

n = int(input())        //输入二维数组的行数和列数
line = [[0]*n]*n        //初始化二维数组
for i in range(n):
    line[i] = input().split(" ")       //输入二维数组,同行数字用空格分隔,不同行则用回车换行
    line[i] = [int(j) for j in line[i]]    //将数组中的每一行转换成整型
print(line)            //打印二维数组
Copy after login

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!

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