簡體   English   中英

類型錯誤:元組索引必須是整數或切片,而不是 str

[英]TypeError: tuple indices must be integers or slices, not str

我需要創建一個函數來更新元組列表中的元組。 元組包含交易,交易以數量、日期和類型為特征。 我創建了這個函數,它應該用一個新的元組完全替換一個元組,但是當我嘗試打印更新的元組列表時,出現錯誤:

TypeError: tuple indices must be integers or slices, not str

代碼:

def addtransaction(transactions, ammount, day, type): 
    newtransactions = {
        "Ammount": ammount,
        "Day": day,
        "Type": type
        }
   transactions.append(newtransaction)

def show_addtransaction(transactions):
     Ammount = float(input("Ammount: "))
     Day = input("Day: ")
     Type = input("Type: ")
    addtransaction(transactions, ammount, day, type)

def show_all_transaction(transactions):
    print()
    for i, transaction in enumerate(transactions):
        print("{0}. Transaction with the ammount of {1} on day {2} of type:     {3}".format(
            i + 1,
            transaction['Ammount'], ; Here is where the error occurs.
            transaction['Day'],
            transaction['Type']))

def update_transaction(transactions): ; "transactions" is the list of tuples
    x = input("Pick a transaction by index:") 
    a = float(input("Choose a new ammount:"))
    b = input("Choose a new day:")
    c = input("Choose a new type:")
    i = x
    transactions[int(i)] = (a, b, c)

addtransaction(transactions, 1, 2, service)
show_all_transaction(transactions)
update_transaction(transactions)
show_all_transaction(transactions)

元組基本上只是一個list ,不同之處在於在tuple您不能在不創建tuple情況下覆蓋其中的值。

這意味着您只能通過從 0 開始的索引訪問每個值,例如transactions[0][0]

但看起來你應該首先使用dict 所以你需要重寫update_transaction來實際創建一個類似於addtransaction工作方式的dict 但是不是將新事務添加到最后,您只需要覆蓋給定索引處的事務。

這是update_transaction已經做的,但它用元組而不是dict覆蓋它。 當您打印出來時,它無法處理並導致此錯誤。

原始答案(在我知道其他功能之前)

如果要使用字符串作為索引,則需要使用dict 或者,您可以使用namedtuple ,它類似於元組,但它也具有每個值的屬性,其中每個值都具有您之前定義的名稱。 所以在你的情況下,它會是這樣的:

from collections import namedtuple
Transaction = namedtuple("Transaction", "amount day type")

用於創建Transaction的字符串給出的名稱,並用空格或逗號(或兩者)分隔。 您可以通過簡單地調用該新對象來創建事務。 並通過索引或名稱訪問。

new_transaction = Transaction(the_amount, the_day, the_type)
print(new_transaction[0])
print(new_transaction.amount)

請注意,執行new_transaction["amount"]仍然無效。

這不是一個通用的答案,如果有人遇到同樣的問題,我會提到它。

如前所述,元組由整數尋址,例如my_tuple[int]或切片my_tuple[int1:int2]

當我將代碼從 Python2 移植到 Python3 時遇到了麻煩。 原始代碼使用了類似my_tuple[int1/int2] ,這在 Python2 中有效,因為除法 int/int 結果為 int。 在 Python3 中 int/int 結果是一個浮點數。 我必須將代碼修復為my_tuple[int1//int2]以獲得 python2 行為。

暫無
暫無

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

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