我需要创建一个函数来更新元组列表中的元组。元组包含以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)
元组基本上只是一个
list
,区别在于在tuple
中,如果不创建新的tuple
,就不能覆盖其中的值。这意味着您只能通过从0开始的索引来访问每个值,比如
transactions[0][0]
。但是看起来你应该首先使用
dict
。所以您需要重写update_transaction
来实际创建一个dict
类似于addtransaction
工作方式的dict
。但是,您只需要在给定索引处覆盖事务,而不是将新事务添加到末尾。这就是
update_transaction
已经做的,但是它用元组而不是dict
覆盖它。当你把它打印出来时,它无法处理并导致这个错误。原始答案(在我知道其他功能之前)
如果要将字符串用作索引,则需要使用} ,它类似于元组,但它也为每个值都有一个与前面定义的名称相同的属性。所以在你的情况下应该是:
dict
。或者,您可以使用^{由用于创建
Transaction
的字符串给出并用空格或逗号(或两者)分隔的名称。只需调用那个新对象就可以创建事务。通过索引或名称访问。请注意,执行
new_transaction["amount"]
仍然不起作用。相关问题 更多 >
编程相关推荐