簡體   English   中英

python中的二維數組

[英]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")

前兩個任務工作正常。 但是當我嘗試執行arr[1].append("bb1") ,出現以下錯誤:

IndexError: list index out of range.

我在嘗試聲明二維數組時做了什么傻事嗎?

編輯:
但我不知道數組中的元素數(行和列)。

你不要在 python 中“聲明”數組或其他任何東西。 您只需分配給(新)變量。 如果你想要一個多維數組,只需添加一個新數組作為數組元素。

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

要么

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

Python 中沒有這樣的多維數組,您擁有的是一個包含其他列表的列表。

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

您所做的是聲明一個包含單個列表的列表。 所以arr[0]包含一個列表,但arr[1]沒有定義。

您可以定義一個包含兩個列表的列表,如下所示:

arr = [[],[]]

或者定義一個更長的列表,你可以使用:

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

不應該做的是:

arr = [[]] * 3

因為這會將相同的列表放在容器列表中的所有三個位置:

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

你在這里使用的不是數組,而是列表(列表)。

如果你想要 Python 中的多維數組,你可以使用 Numpy 數組。 你需要提前知道形狀。

例如:

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

您嘗試附加到數組中的第二個元素,但它不存在。 創造它。

arr = [[]]

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

我們可以如下動態創建多維數組,

創建 2 個變量以從標准輸入讀取 x 和 y:

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

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

使用以下代碼創建一個初始值填充為 0 或任何值的列表數組

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

為數組數據創建行數和列數。

從標准輸入讀取數據:

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

顯示結果:

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

或使用另一種方式顯示上面動態創建的數組是,

for row in z:
     print(row)

在 Python 中構建多維列表時,我通常使用類似於 ThiefMaster 的解決方案,但不是將項附加到索引0 ,然后將項附加到索引1等,我總是使用索引-1 ,它自動是最后一個的索引數組中的項。

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")

將產生你所追求的二維數組(實際上是一個列表列表)。

您可以先將元素追加到初始化的數組中,然后為方便起見,您可以將其轉換為 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)]

用於競爭性編程

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 i in range(0,row):
    for j in range(0,len(main_list[0]):
        print main_list[i][j],
        print

上述方法不適用於 for 循環,我想在 if 條件下將數據從二維數組傳輸到新數組。 這種方法會奏效

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")

就我而言,我必須這樣做:

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

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM