簡體   English   中英

TypeError:'int'對象在python中引用二維數組時不可下標

[英]TypeError: 'int' object is not subscriptable while refrencing 2d array in python

我試圖在參賽者人數和分數列表中找到最低分。 在第 6 行,我收到錯誤消息:

if score[u[1]] == score[0]:
TypeError: 'int' object is not subscriptable

我正在嘗試使用循環檢查整個二維數組,以找到哪個分數與授予的最低分數相匹配並檢索參賽者編號

for x in range(contestants):
    CN = x+1
    score1.insert(x,[[CN],[score[x]]])
    score.sort
    for u in score:
        if score[u[1]] == score[0]:
            KO = score[u[0]]
            print (KO)

分數看起來像這樣:

 for i in range (contestants):
    j1 = int(input("Judge 1 enter your score for the contestant: "))
    j2 = int(input("Judge 2 enter your score for the contestant: "))
    j3 = int(input("Judge 3 enter your score for the contestant: "))
    j4 = int(input("Judge 4 enter your score for the contestant: "))
    j5 = int(input("Judge 5 enter your score for the contestant: "))
    print("Round over, next contstant")
    scores = [j1,j2,j3,j4,j5]

    scoreJ1.append(scores[0])
    scoreJ2.append(scores[1])
    scoreJ3.append(scores[2])
    scoreJ4.append(scores[3])
    scoreJ5.append(scores[4])


    scores.sort()
    scores.pop(0)
    scores.pop(3)
    #proud of this
    score.insert(i,scores[1]+scores[2]+scores[0])

謝謝您的幫助。

您收到的錯誤消息是TypeError: 'int' object is not subscriptable 讓我們分解一下:

  • TypeError告訴您您正試圖在某處應用不適當的操作
  • is not subscriptable告訴您不適當的操作是在某事之后放置一對[ ]
  • 'int' object is not subscriptable告訴您您正在嘗試對 int 執行此操作。

現在讓我們考慮產生此錯誤的代碼行:

if score[u[1]] == score[0]:

請注意,在某物之后直接放置了三對[ ] :其中之一必須具有int類型。 因此有3名候選人

  1. score
  2. u
  3. score

因此,我們得出結論,要么score要么u是整數。

查看您提供的上下文

for u in score:

如果score不是一些可迭代的,這條線就會失敗。 int不可迭代,因此我們得出結論score不是整數。 這使我們得出結論u (它是容器score某個元素)是一個整數。

關於您的代碼的其他評論(其中包含許多問題):

  1. score1懷疑的是,您在一行中引用了score1 (您在其他任何地方都沒有引用它),而在下一行中使用了score 你確定前者不應該只是score嗎?

  2. score.sort訪問scoresort方法但不調用它。 如果您想將該方法存儲在某處或將其傳遞到某處,這在 Python 中是有意義的,但您並沒有這樣做。 所以你幾乎肯定忘記了調用這個函數:你可以通過在它后面添加()做到這一點,就像這樣: store.sort()

  3. 在你的第二個代碼塊scoreJ1和朋友似乎沒有在任何地方定義,所以這個代碼不能工作,除非你沒有顯示其他東西。

這應該給你很多思考。

暫無
暫無

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

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