簡體   English   中英

為什么不能在python中將元組轉換為int?

[英]Why can't convert a tuple to a int in python?

我的 python 代碼正在將一個隨機生成的數字更改為int ,但隨后數組認為它是一個tuple 我不知道為什么。

import random

board_state = []
width = 5
height = 5

def dead_state():
    for i in range(0, height):
        board_row = []
        for j in range(0, width):
            board_row.append(0)
        board_state.append(board_row)

def random_state():
    dead_state()
    interator = int(round(random.random() * 5) + 3)
    for i in range(0, interator):
        width_Select_Test = round(random.random() * width)
        height_Select_Test = round(random.random() * height)
        width_Select_Test = int(width_Select_Test)
        height_Select_Test = int(height_Select_Test)
        print(type(width_Select_Test))
        print(type(height_Select_Test))

        board_state[height_Select_Test, width_Select_Test] = 1

random_state()
print(board_state)

轉換后的打印語句說它是一個整數,但隨后在數組中拋出一個錯誤,說它是一個元組。

錯誤信息是正確的:

...
board_state[height_Select_Test, width_Select_Test] = 1
TypeError: list indices must be integers or slices, not tuple

這里的“元組”是什么? 組合height_Select_Test, width_Select_Test

除了在其他語言中(然后又相當於,erm,還有其他語言),在 Python 中你不使用逗號來表示二維數組。 您必須使用雙索引:

board_state[height_Select_Test][width_Select_Test]

因為board_state每個列表board_state都是一個子列表。

TLDR:您應該使用board_state[height_Select_Test][width_Select_Test]而不是board_state[height_Select_Test, width_Select_Test]訪問它。

為什么 原因:在 Numpy 中,我們可以使用 arr[x,y...z] 索引一個高維數組,具體取決於它的維數。 但是,本例中的board_state是一個列表列表。 你仍然需要指數的整數元素妥善首先訪問i_th列出的這份名單,然后名單內j_th元素內i_th列表。 因此,只有arr[i][j]有效,而arr[i, j]無效arr[i, j]后者通常在numpy或其他深度學習框架中得到支持。 (改天再說)

如上所述,您需要使用[x][y]而不是[x, y] ,它們相等。

您的代碼仍然會失敗,因為您生成的隨機數可能大於列表的長度。 因此,我添加了-1來糾正該偏移量。

為了更好的代碼,不要使用range(0, variable) ,它等於range(variable)

改進的功能代碼:

import random

board_state = []
width = 5
height = 5

def dead_state():
    for i in range(height):
        board_row = []
        for j in range(width):
            board_row.append(0)
        board_state.append(board_row)

def random_state():
    dead_state()
    interator = int(round(random.random() * 5) + 3)
    for i in range(interator):
        width_Select_Test = round(random.random() * width)
        height_Select_Test = round(random.random() * height)
        width_Select_Test = int(width_Select_Test)
        height_Select_Test = int(height_Select_Test)

        board_state[height_Select_Test-1][width_Select_Test-1] = 1

random_state()
print(board_state)

暫無
暫無

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

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