【问题标题】:Is there an alternate way to input the index without using a variable? [duplicate]是否有另一种方法可以在不使用变量的情况下输入索引? [复制]
【发布时间】:2019-10-30 03:17:32
【问题描述】:

我必须将货物存储在一个列表中,例如名称和数量,当我创建销售时,程序会询问产品名称,从列表中匹配它,找到索引号并使用索引号找到它的数量。但是我不知道如何在不使用变量的情况下将索引号转移到quantity()。

除了变量,我也尝试使用TM.index(a)。但到目前为止我只能发现Quantity()只允许数字。

TM=[fish,crabs ]  

 Quantity=[100,20  ]

 TM2=input("product name :")

 if TM2.lower() in TM:

      a=TM2.lower()

      b = TM.index(a)

      c = Quantity(b)

我希望输出是这样的:

TM2= Crabs

a= crabs

b= 1

c=Quantity(1)

c=20

但我得到了:TypeError: 'list' object is not callable

【问题讨论】:

  • Quantity[b] ?
  • b 是包含索引的变量。如果我有 100 条鱼和 20 只螃蟹,那么如果我将它们放在两个不同的列表中:TM=[fish,crabs] 和 Quantity=[100,20] .理论上,如果我找到 TM 的索引,我可以使用存储在变量 b 中的索引号来查找数量。例如:TM(0)=fish 所以 Quantity(0)=100。
  • 是的,但是“数量”不是一种方法,而是一个列表。您应该将其索引为 Quantity[b] 而不是 Quantity(b)
  • 错误不是因为您使用变量来访问列表元素,而是使用括号而不是方括号。见骗子。
  • 我假设使用 ( ) 是正确的方法,可能是因为之前我使用了 .append() 和 . count()。另外,我认为使用[]会彻底改变列表,例如:Quantity[b],会导致列表Quantity[100,20]变成Quantity[b]

标签: python


【解决方案1】:

您遇到了麻烦,因为您使用了错误的数据结构。你想要一个dictionary。它的工作原理是这样的:

product_to_quantity = {
    'fish': 100,
    'crabs': 20
}

which = input('product name? ').lower()

quantity = product_to_quantity[which]

print(quantity)

如果你运行这个并输入fish,它将打印100。

注意方括号[],而不是括号()。方括号用于从字典和列表中获取项目。在您的原始代码中,您将使用 Quantity[b] 来获取列表的 bth 元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-05
    • 2021-11-22
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多