我创建了一个程序来接收餐厅预订信息,但是我想按时间顺序对预订进行排序。
该函数以-txt.file
作为参数,文件内容遵循以下结构-
"name", "time", "status"
("status"
是CONFIRMED
或CANCELLED
)。仅应显示CONFIRMED
个保留,并按"time"
对其进行排序。到目前为止,我已经能够显示预订,但是我只是不知道如何对它们进行排序。
def show_reservations(filename):
with open(filename) as file:
content = file.readlines()
for reservation in content:
dictionary = {}
if ", CONFIRMED" in reservation:
dictionary.setdefault(reservation[:-12], "CONFIRMED")
empty_list = []
for k, v in dictionary.items():
print(k)
print(show_reservations(blabla.txt))
-txt.file的任意内容:
MARTIN, 19, CONFIRMED
JULIE, 18, CONFIRMED
METTE, 17, CANCELLED
所需的输出:
JULIE, 18
MARTIN, 19
答案 0 :(得分:1)
如果您将每个保留作为具有两个键值对的字典存储,并将它们存储到列表中,则下面的代码将起作用。
sorted()允许您对预订列表进行排序。然后,您可以通过使用lambda指定排序因子来选择排序因子。 :)
def show_reservations(filename):
with open(filename) as file:
content = file.readlines()
# list to store confirmed reservations
confirmed_list = []
for reservation in content:
# dict to be re-used to parse each reservation
r = {}
if ", CONFIRMED" in reservation:
# splits each line to a list e.g. ["JULIE", "16", "CONFIRMED"]
reserv = reservation.split(",")
# gets first element which is the name of customer and stores in dict
# strip is to remove any leading/trailing whitespace
r['name'] = reserv[0].strip()
# gets second element which is the time of reservation and stores in dict
r['time'] = reserv[1].strip()
# appends dict to list
confirmed_list.append(r)
# sorts the list of confirmed reservations by time using lambda
confirmed_list_s = sorted(confirmed_list, key=lambda k: k['time'])
for r in confirmed_list_s:
# prints out each reservation in sorted list
row = ", ".join(val for key, val in r.items())
print(row)
show_reservations("blabla.txt")
输出:
JO, 16
JULIE, 18
MARTIN, 19
CHARLIE, 20