繁体   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