类型错误:元组索引必须是整数或切片,而不是s

2024-05-29 01:49:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个函数来更新元组列表中的元组。元组包含以amount、day和type为特征的事务。我做的这个函数应该完全用一个新的元组替换一个元组,但是当我试图打印更新的元组列表时,我得到了一个错误:

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)

Tags: theinputdeftypeshowalltransaction元组
1条回答
网友
1楼 · 发布于 2024-05-29 01:49:46

元组基本上只是一个list,区别在于在tuple中,如果不创建新的tuple,就不能覆盖其中的值。

这意味着您只能通过从0开始的索引来访问每个值,比如transactions[0][0]

但是看起来你应该首先使用dict。所以您需要重写update_transaction来实际创建一个dict类似于addtransaction工作方式的dict。但是,您只需要在给定索引处覆盖事务,而不是将新事务添加到末尾。

这就是update_transaction已经做的,但是它用元组而不是dict覆盖它。当你把它打印出来时,它无法处理并导致这个错误。

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

如果要将字符串用作索引,则需要使用dict。或者,您可以使用^{},它类似于元组,但它也为每个值都有一个与前面定义的名称相同的属性。所以在你的情况下应该是:

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"]仍然不起作用。

相关问题 更多 >

    热门问题