创建取决于变量的列表

2024-04-16 16:20:58 发布

您现在位置:Python中文网/ 问答频道 /正文

实际上我有一个问题,因为我想在函数中创建一个列表,但它取决于一个变量,我的意思是。。。有了一个输入,我想定义变量的值,有了代码,我模拟了一家餐馆的程序,为一张桌子提供服务,我应该能够把他们要的食物添加到每一张桌子的列表中。这是我的代码:

foodlist = []
table_1 = []
table_2 = []
table_3 = []
table_4 = []
table_5 = []
table_6 = []
p = 0

def openFile():
    file = open("cartarest.txt","r",1,"utf-8")
    line = file.readline().strip()
    while line != "":    
        parts = line.split(";")
        name = parts[0]
        price = int(parts[1])
        type = parts[2]     
        foodlist.append(parts)
        line = file.readline().strip()
        p += 1
    return (foodlist,p)

def serveTable(x):
    print("The menu of the restaurant is:")
    print(foodlist)
    add = input("Which food do you want to add?: ")
    while add != 0:
        for i in range(p):
            if add.lower() == foodlist[i][0]:
                **table_+x.append(foodlist[i])**
        add = input("Which food do you want to add?: ")

openFile()
tableserve = input("What table do you want to attend?")
while tableserve.lower() != "cerrar":
    serveTable(tableserve)
    tableserve = input("What table do you want to attend?")

EDIT:我已经解决了变量'p'的问题,但是现在我有一个问题,如何限制表的范围,因为我试着输入一个像“-1”这样的值,并且代码正常运行,它不应该工作,只使用1到6之间的值(显然使用@Tim的答案)


Tags: to代码youadd列表inputlinetable
1条回答
网友
1楼 · 发布于 2024-04-16 16:20:58

使用列表列表代替6个表变量,并将表编号作为索引传递:

tables = [[] for _ in range(ntables)]
def serveTable(x):
    print("The menu of the restaurant is:")
    print(foodlist)
    add = input("Which food do you want to add?: ")
    while add != 0:
        for i in range(p):
            if add.lower() == foodlist[i][0]:
                tables[x].append(foodlist[i])
        add = input("Which food do you want to add?: ")

相关问题 更多 >