Python,自动数组形成数据检索错误

问题描述 投票:0回答:1

我正在尝试创建2d数组,然后从该数组中提取数据并在该数组中的特定点插入数据。下面是我为创建2D数组编写的一些代码:

from array import *
import math, random

TDArrayBuilder = []
TDArray = []
for yrunner in range(3):
    for xrunner in range(3):
        TDArrayBuilder.append(random.randint(0,1))
    TDArray.insert(yrunner, [TDArrayBuilder])
    TDArrayBuilder = []

print(TDArray[0][2])

这是吐出来​​的错误如下:

追踪(最近通话):文件“ C:/TestFile.py”,第13行,在打印(TDArray [0] [2])IndexError:列表索引超出范围

在此之前,我还写了一些代码来查找和打印2D数组中的最小值和最大值,因此很容易就能在指定位置打印该值。我很确定这只是因为我使用了numpy,但我仍然想在没有numpy的情况下进行此操作。

示例代码:

import numpy as np  #required Import
import math
#preset matrix data
location = []       #Used for locations in searching
arr = np.array([[11, 12, 13],[14, 15, 16],[17, 15, 11],[12, 14, 15]]) #Data matrix
result = np.where(arr == (np.amax(arr)))    #Find the position(s) of the lowest data or the highest data, change the np.amax to npamin for max or min respectively
listofCoordinates = list(zip(result[0], result[1])) #Removes unnecessary stuff from the list
for cord in listofCoordinates:  #takes the coordinate data out, individually
    for char in cord:           #loop used to separate the characters in the coordinate data
        location.append(char)   #Stores these characters in a locator array

length = (len(location))                #Takes the length of location and stores it
length = int(math.floor((length / 2)))  #Floors out the length / 2, and changes it to an int instead of a float
for printer in range(length):           #For loop to iterate over the location list
    ycoord = location[(printer*2)]      #Finds the row, or y coord, of the variable
    xcoord = location[((printer*2)+1)]  #Finds the column, or x coord of the variable
    print(arr[ycoord][xcoord])          #Prints the data, specific to the location of the variables

摘要:

我希望能够从2d数组中检索数据,但我不知道该怎么做(关于第一个代码)。我使用numpy制作了一个文件,并且可以正常工作,但是从目前开始,我不希望将其用于此操作。会有帮助

python arrays numpy data-retrieval
1个回答
0
投票
from random import randint

TDArray = list()
for yrunner in range(3):
    TDArrayBuilder = list()
    for xrunner in range(3):
        TDArrayBuilder.append(randint(0, 1))
    TDArray.insert(yrunner, TDArrayBuilder)

print(TDArray)
print(TDArray[0][2])

TDArray = [[randint(0, 1) for _ in range(3)] for _ in range(3)]
print(TDArray)
print(TDArray[0][2])
© www.soinside.com 2019 - 2024. All rights reserved.