简体   繁体   中英

Two dimensional array in python

I want to know how to declare a two dimensional array in 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:

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. 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.

>>> 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.

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. 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:

 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

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.

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.

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

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

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. 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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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