gpt4 book ai didi

python - 创建依赖于变量的列表

转载 作者:太空宇宙 更新时间:2023-11-04 00:06:51 24 4
gpt4 key购买 nike

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

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?")

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

最佳答案

代替 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?: ")

关于python - 创建依赖于变量的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53838318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com