【问题标题】:append a list with user input附加用户输入的列表
【发布时间】:2021-03-16 00:53:41
【问题描述】:

我的任务是将用户输入添加到列表中最近选择的号码。例如:

if choice == 1:
    table = int(input("Please select your table number(0-19): "))
    if tables[i] == "AVAILABLE":
        name = input("What is your name?: ")
        tables.append(name)

当我运行它时,输入被附加到最后一个表选项,而不是用户选择的选项。例如,表选择是 5,用户名是“Sam” - Sam 显示在表 20 而不是表 5。

我应该使用 tables.insert 吗?对此有点失落。谢谢。

这是迄今为止的全部代码:

while True:
print("")
print("Welcome to Torrey's Restaurant")
print("=====Select Option to Continue=====")    
print("1- Reserve a Table")
print("2- Clear Reservation")
print("3- Status of Tables")
print("0- Exit")
choice = int(input("Choice? "))

count = 0
tables = []

for i in range(20):
    tables.append("AVAILABLE")     

if choice == 0:
    print("Thank you for using this program")
    break
    
if choice == 1:
    table = int(input("Please select your table number(0-19): "))
    if tables[i] == "AVAILABLE":
        name = input("What is your name?: ")
        tables.append(name)
    if not tables[i] == "AVAILABLE":
        print("The table you selected is unavailable")

tables{i} = 可以保留或已保留的表的列表。

【问题讨论】:

  • 你在使用 Python 吗?
  • 是的,我正在使用 python,抱歉。
  • tables[i] 是什么意思?

标签: python list input append


【解决方案1】:

使用inser() 代替append() 将名称插入列表。

if choice == 1:
    table = int(input("Please select your table number(0-19): "))
    if table in tables :
        name = input("What is your name?: ")
        tables.insert(table,name)
        print(tables)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
Please select your table number(0-19): 1
What is your name?: Alex
[0, 'Alex', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

【讨论】:

  • 谢谢。如果表中的表[i],这实际上是必需的:
  • 好的。我刚刚修改了该部分,因为我不知道您如何将数据存储在列表中。我认为您需要 insert() 部分。
  • 是的。很抱歉不包括存储的数据。插入工作。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-04-12
  • 2020-01-09
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多