python - 类型错误 : tuple indices must be integers or slices, 不是 str

标签 python

我需要创建一个函数来更新元组列表中的元组。元组包含交易,其特征为金额、日期和类型。我创建了这个函数,应该用新的元组完全替换元组,但是当我尝试打印更新的元组列表时,我收到错误:

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/

相关文章:

python - scipy:没有框架,轴,只有内容的savefig

python - 使用 int|abs 时 Ansible Jinja 错误

python - 我用 pip install 安装的包显示没有模块

python - 使用 Python over Apache 通过 HTTP 将文件推送给用户时文件名错误

python - 加法和 += 给出列表的不同结果(深度优先搜索)

python - 如何在 django 模板中转义 {{ 或 }}?

python - 使用 flags() 创建一个 QTableWidgetItem

python - 从日期时间转换为 GPS 时间

递归中的python列表

python - 类型错误 : object of type 'IMapIterator' has no len() for pool. imap