我想重用已经修改过的数组

时间:2017-04-01 18:44:02

标签: python list

我正在使用Python制作影院预订系统,但我在保存已修改的阵列时遇到问题,因此它显示座位已被占用我正在使用它来创建阵列。

def seats():
    rows = "ABCDE"
    columns = range(0, 10)
    x = [{ltr + str(y): 'Empty' for ltr in rows} for y in columns]
    pprint(x)
    res = str(raw_input("Pick a seat "))
    if res[1] == '0':
        if x[0][res] == 'Taken':
            print ('Seat taken')
    else:
       x[0][res] = 'Taken'

请注意,我不是那么有经验,所以任何使代码更清洁的提示也会被评估。客户应该能够购买多个座位并且我已经整理好了,但如果我返回菜单然后再回到座位,那么所有“被采取”的座位再次显示为“空”。

1 个答案:

答案 0 :(得分:0)

也许您希望将其放在一个类中并将x定义为属性。我已经改变了很多,不太确定这是否是你想要的。例如,我已将x重命名为self.seats,并将其结构更改为dict而不是list dict,因为对我来说似乎更容易。

#!/usr/bin/env python3
class Cinema(object):

     def __init__(self, rows, columns):
         self.rows = rows
         self.columns = columns
         # True: seat is free, seat is availbale
         self.seats = {"{row}{col}".format(row=row, col=col): True for row in rows for col in columns}

     def ask_for_seat(self):
         print("The following seats are still available:")
         self.print_free_seats()
         seat = input("Pick a seat: ")
         if seat in self.seats:
             if self.seats[seat]:
                 print("Thank you. We are reserving seat {} for you.".format(seat))
                 self.seats[seat] = False
                 return seat
             else:
                 print("Seat {} is already reserved. Please choose another one.".format(seat))
                 return self.ask_for_seat()
         else:
             print("Sorry, this cinema does not have a seat {}. Please choose another one.".format(seat))
             return self.ask_for_seat()

     def print_free_seats(self):
         for row in self.rows:
             for col in self.columns:
                 seat = "{row}{col}".format(row=row, col=col)
                 if self.seats[seat]:
                     print(seat, end=" ")
                 else:
                     print(" "*len(seat), end=" ")
             print()


if __name__=='__main__':
     c = Cinema("ABCDE", range(0, 10))
     while True:
         c.ask_for_seat()

请注意,这是Python 3代码,不适用于Python 2.