也許你想把它放在一個類中,並將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.工作
你帶*名單工作*。我不確定你問的是什麼問題,但是我懷疑是因爲你的函數只有局部變量,並且沒有返回任何東西,所以你看不到任何東西效果。 –
在**座位**功能之外初始化** x **,並將其作爲參數傳入 –
另外,在我看來,您只能使用第一行,不是? –