简体   繁体   English

python中的二维数组

[英]Two dimensional array in python

I want to know how to declare a two dimensional array in Python.我想知道如何在 Python 中声明一个二维数组。

arr = [[]]

arr[0].append("aa1")
arr[0].append("aa2")
arr[1].append("bb1")
arr[1].append("bb2")
arr[1].append("bb3")

The first two assignments work fine.前两个任务工作正常。 But when I try to do, arr[1].append("bb1") , I get the following error:但是当我尝试执行arr[1].append("bb1") ,出现以下错误:

IndexError: list index out of range.

Am I doing anything silly in trying to declare the 2-D array?我在尝试声明二维数组时做了什么傻事吗?

Edit:编辑:
but I do not know the number of elements in the array (both rows and columns).但我不知道数组中的元素数(行和列)。

You do not "declare" arrays or anything else in python.你不要在 python 中“声明”数组或其他任何东西。 You simply assign to a (new) variable.您只需分配给(新)变量。 If you want a multidimensional array, simply add a new array as an array element.如果你想要一个多维数组,只需添加一个新数组作为数组元素。

arr = []
arr.append([])
arr[0].append('aa1')
arr[0].append('aa2')

or要么

arr = []
arr.append(['aa1', 'aa2'])

There aren't multidimensional arrays as such in Python, what you have is a list containing other lists. Python 中没有这样的多维数组,您拥有的是一个包含其他列表的列表。

>>> arr = [[]]
>>> len(arr)
1

What you have done is declare a list containing a single list.您所做的是声明一个包含单个列表的列表。 So arr[0] contains a list but arr[1] is not defined.所以arr[0]包含一个列表,但arr[1]没有定义。

You can define a list containing two lists as follows:您可以定义一个包含两个列表的列表,如下所示:

arr = [[],[]]

Or to define a longer list you could use:或者定义一个更长的列表,你可以使用:

>>> arr = [[] for _ in range(5)]
>>> arr
[[], [], [], [], []]

What you shouldn't do is this:不应该做的是:

arr = [[]] * 3

As this puts the same list in all three places in the container list:因为这会将相同的列表放在容器列表中的所有三个位置:

>>> arr[0].append('test')
>>> arr
[['test'], ['test'], ['test']]

What you're using here are not arrays, but lists (of lists).你在这里使用的不是数组,而是列表(列表)。

If you want multidimensional arrays in Python, you can use Numpy arrays.如果你想要 Python 中的多维数组,你可以使用 Numpy 数组。 You'd need to know the shape in advance.你需要提前知道形状。

For example:例如:

 import numpy as np
 arr = np.empty((3, 2), dtype=object)
 arr[0, 1] = 'abc'

You try to append to second element in array, but it does not exist.您尝试附加到数组中的第二个元素,但它不存在。 Create it.创造它。

arr = [[]]

arr[0].append("aa1")
arr[0].append("aa2")
arr.append([])
arr[1].append("bb1")
arr[1].append("bb2")
arr[1].append("bb3")

We can create multidimensional array dynamically as follows,我们可以如下动态创建多维数组,

Create 2 variables to read x and y from standard input:创建 2 个变量以从标准输入读取 x 和 y:

 print("Enter the value of x: ")
 x=int(input())

 print("Enter the value of y: ")
 y=int(input())

Create an array of list with initial values filled with 0 or anything using the following code使用以下代码创建一个初始值填充为 0 或任何值的列表数组

z=[[0 for row in range(0,x)] for col in range(0,y)]

creates number of rows and columns for your array data.为数组数据创建行数和列数。

Read data from standard input:从标准输入读取数据:

for i in range(x):
         for j in range(y):
             z[i][j]=input()

Display the Result:显示结果:

for i in range(x):
         for j in range(y):
             print(z[i][j],end=' ')
         print("\n")

or use another way to display above dynamically created array is,或使用另一种方式显示上面动态创建的数组是,

for row in z:
     print(row)

When constructing multi-dimensional lists in Python I usually use something similar to ThiefMaster's solution, but rather than appending items to index 0 , then appending items to index 1 , etc., I always use index -1 which is automatically the index of the last item in the array.在 Python 中构建多维列表时,我通常使用类似于 ThiefMaster 的解决方案,但不是将项附加到索引0 ,然后将项附加到索引1等,我总是使用索引-1 ,它自动是最后一个的索引数组中的项。

ie IE

arr = []

arr.append([])
arr[-1].append("aa1")
arr[-1].append("aa2")

arr.append([])
arr[-1].append("bb1")
arr[-1].append("bb2")
arr[-1].append("bb3")

will produce the 2D-array (actually a list of lists) you're after.将产生你所追求的二维数组(实际上是一个列表列表)。

You can first append elements to the initialized array and then for convenience, you can convert it into a numpy array.您可以先将元素追加到初始化的数组中,然后为方便起见,您可以将其转换为 numpy 数组。

import numpy as np
a = [] # declare null array
a.append(['aa1']) # append elements
a.append(['aa2'])
a.append(['aa3'])
print(a)
a_np = np.asarray(a) # convert to numpy array
print(a_np)
a = [[] for index in range(1, n)]

For compititve programming用于竞争性编程

1) For input the value in an 2D-Array 1) 用于输入二维数组中的值

row=input()
main_list=[]
for i in range(0,row):
    temp_list=map(int,raw_input().split(" "))
    main_list.append(temp_list)

2) For displaying 2D Array 2) 用于显示二维数组

for i in range(0,row):
    for j in range(0,len(main_list[0]):
        print main_list[i][j],
        print

the above method did not work for me for a for loop, where I wanted to transfer data from a 2D array to a new array under an if the condition.上述方法不适用于 for 循环,我想在 if 条件下将数据从二维数组传输到新数组。 This method would work这种方法会奏效

a_2d_list = [[1, 2], [3, 4]]
a_2d_list.append([5, 6])
print(a_2d_list)

OUTPUT - [[1, 2], [3, 4], [5, 6]]
x=3#rows
y=3#columns
a=[]#create an empty list first
for i in range(x):
    a.append([0]*y)#And again append empty lists to original list
    for j in range(y):
         a[i][j]=input("Enter the value")

In my case I had to do this:就我而言,我必须这样做:

for index, user in enumerate(users):
    table_body.append([])
    table_body[index].append(user.user.id)
    table_body[index].append(user.user.username)

Output:输出:

[[1, 'john'], [2, 'bill']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM