简体   繁体   English

多维数组索引

[英]Multi-dimensional array indexing

working on an algorithm to deal 6 cards from a standard deck and compare the deals combinations to a target prime.The code bugs up due to the indexing of the Permutation array "Result".Any suggestions? 正在研究一种算法,可以从标准卡片组中分发6张牌,并将交易组合与目标素数进行比较。由于对排列数组“结果”的索引,该代码错误了。有什么建议吗?

import random
cards=[1,2,3,4,5,6,7,8,9,10,11,12,13,1,2,3,4,5,6,7,8,9,
10,11,,12,13,1,2,3,4,5,6,7,8,9,10,11,12,13,1,2,3,4,5,6,7,8,9,10,11,12,13]

deal=[0,0,0,0,0,0]

for i in range(0,6):
    deal[i]=cards.pop(random.randint(0,len(cards)-1))
    print(deal)
Result = [[0 for x in range(3)] for x in range(256)] 

Result[0][0]= deal[0]+deal[1]
Result[0][1]= deal[0]-deal[1]
Result[0][2]= deal[0]*deal[1]
Result[0][3]= deal[0]/deal[1]



for i in range(2,5):
    for j in range(2^(2*j),256):
                   Result[0][j]= Result[0][j]+deal[i]
                   Result[1][j]= Result[0][j]-deal[i]
                   Result[2][j]= Result[0][j]*deal[i]
                   Result[3][j]= Result[0][j]/deal[i]
                   print(Result)

The error message is : Traceback (most recent call last): File "C:/Users/xxx/Desktop/Dealhit.py", line 16, in Result[0][3]= deal[0]/deal[1] 错误消息是:追溯(最近一次呼叫最近):文件“ C:/Users/xxx/Desktop/Dealhit.py”,第16行,结果[0] [3] = Deal [0] / deal [1]

IndexError: list index out of range. IndexError:列表索引超出范围。 Which creats a [4x1024] array of mostly empty values. 这将创建一个[4x1024]数组,其中大多数都是空值。

for j in range(len(Result-1)):

Should be 应该

for j in range(len(result)-1):

Otherwise (result - 1) will be exucuted before len(result) . 否则,将在len(result)之前引用(result - 1) len(result) Resulting in TypeError: unsupported operand type(s) for -: 'list' and 'int' 导致TypeError: unsupported operand type(s) for -: 'list' and 'int'

Because i is in range(5) , i can take the value 4, which, added to 2, gives 6, which is out of the bounds of deal . 因为irange(5) ,所以i可以取值4,将其加到2得出6,这超出了deal范围。

I would recommend replacing 我建议更换

range(5)

by 通过

range(len(deal) - 2)

You'll have another problem after that, when you try to assign Result[1][j] , because Result contains only one element. 之后,当您尝试分配Result[1][j] ,您将遇到另一个问题,因为Result仅包含一个元素。 You need to either create a full 2d matrix of the size you need, or append items dynamically. 您需要创建所需大小的完整2D矩阵,或者动态附加项。

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

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