我需要创建一个函数来更新元组列表中的元组。元组包含交易,其特征为金额、日期和类型。我创建了这个函数,应该用新的元组完全替换元组,但是当我尝试打印更新的元组列表时,我收到错误:
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)
最佳答案
元组基本上只是一个列表
,不同之处在于,在元组
中,如果不创建新的元组
,则无法覆盖其中的值>.
这意味着您只能通过从 0 开始的索引访问每个值,例如 transactions[0][0]
。
但看起来你实际上应该首先使用 dict
。因此,您需要重写 update_transaction
以实际创建一个 dict
,类似于 addtransaction
的工作方式。但是,您不需要将新事务添加到末尾,您只需覆盖给定索引处的事务即可。
这就是 update_transaction
已经做的事情,但它用元组而不是 dict
覆盖它。当您打印出来时,它无法处理该问题并导致此错误。
原始答案(在我知道其他功能之前)
如果你想使用字符串作为索引,你需要使用dict
。或者您可以使用namedtuple
它类似于元组,但它也为每个值都有一个属性,其名称是您之前定义的。所以在你的情况下,它会是这样的:
from collections import namedtuple
Transaction = namedtuple("Transaction", "amount day type")
由用于创建事务
的字符串给出的名称,并用空格或逗号(或两者)分隔。您只需调用该新对象即可创建交易。并通过索引或名称访问。
new_transaction = Transaction(the_amount, the_day, the_type)
print(new_transaction[0])
print(new_transaction.amount)
请注意,执行 new_transaction["amount"]
仍然不起作用。
关于python - 类型错误 : tuple indices must be integers or slices, 不是 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40308855/