seatList1 = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10 }
我把以上字典作为航空公司的座位清单。一旦用户选择一个空座位并在其中输入他们的姓名和其他详细信息,他们选择的座位的值就会成为他们的名字,例如:
在他们选择之前:
1: 1
后:
1: Tom
以下是我的识别程序。“详细信息”是包含“乘客的”详细信息的字符串。
while (True):
seatNum = int(input("Enter the seat number:"))
if isinstance(seatList1[seatNum], str):
print("This seat has been ordered, please enter another one.")
else:
print("Success")
seatList1[seatNum] = detail
print(seatList1)
break
这样该程序就可以通过一个字符串或整数来识别座位是否为空。但是问题是,我希望这个程序可以在第一次打印空座位,就像这样(假装已经坐了1个座位):
The available seats are 2, 3, 4, 5, 6, 7, 8, 9, 10
这样,“乘客”就可以知道哪些座位可供他们选择。有没有办法在不编写更多列表的情况下解决此问题?非常感谢你!
您可以使用与上面的代码相同的逻辑。如果用户已经预订了该座位,则该座位号的值seatList1
将为字符串。你可以做-
for k, v in seatList1.items():
if not isinstance(v, str):
print (k)
如果您想将可用座位打印为逗号分隔的字符串,则可以使用join()
-
",".join(str(k) for k, v in seatList1.items() if not isinstance(v, str))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句