字符串格式问题(字典)

我有两个独立的txt文件(预订1、预订2),它们的设置类似于餐厅的预订系统。
文件中的每一行代表一个预订,其格式为:`名称、时间、状态`。状态为`CONFIRMED`或`CANCELLED`。
我想编写一个函数`show_Reserve vations`,该函数以字符串`文件名`作为参数,读取名为``文件名``的文件,并按时间顺序打印所有的`CONFIRMED`保留。
这必须是代码的一部分:
"``"
定义SHOW_RESERVATIONS(文件名):
*(在此处编写代码)
Print("从第一个文件开始预订:")
Print(SHOW_RESERVATIONS("Reserve vations1.txt"))
Print("来自第二个文件的预订:")
Print(SHOW_RESERVATIONS("Reserve vations2.txt"))
"``"
以下是我到目前为止所做的工作:
"``"
定义SHOW_RESERVATIONS(文件名):
FILE=打开(文件名)
已确认={}
对于文件中的行:
INFO_PARTS=line.plit(",")
如果INFO_PARTS[2].strie()=="已确认":
已确认[int(INFO_PARTS[1].strie())]=INFO_PARTS[0].strie()
Times=list(confirmed.key())
Times.sorte()
SORTED_CONFERIED={}
对于时间单位:
已排序_已确认[时间]=已确认[时间]
退货已排序_已确认
Print("从第一个文件开始预订:")
Print(SHOW_RESERVATIONS("Reserve vations1.txt"))
Print("来自第二个文件的预订:")
Print(SHOW_RESERVATIONS("Reserve vations2.txt"))
"``"
输出为:
"``"
来自第一个文件的预订:
{17:'Asley',18:'Kira',20:'Jolyn'}
来自第二个文件的预订:
{17:'Codi',18:'Christel',19:'瓦伦丁',20:'Eliseo'}
"``"
它离我想要的很近。但我希望它看起来是这样的:
"``"
来自第一个文件的预订:
阿斯利,17岁
基拉,18岁
乔琳,20岁
来自第二个文件的预订:
Codi,17岁
克里斯特尔,18岁
瓦伦丁,19岁
Eliseo,20岁
"``"
我想解决这个问题,而不必在代码中编写词典。
我该怎么改正呢?

# 回答1


首先,由于您拥有的文件是CSV文件,我建议您使用Python中内置的CSV模块来解析它,因为这会使它更容易。

选择 | 换行 | 行号
  1. import csv
  2.  
  3. def show_reservation(file_path):
  4.     # Using a list of tuples as I'm assuming we can have multiple reservations for the same time
  5.     reservation_info = []
  6.     # Use a context manager here so that you don't 
  7.     # have to remember to close the file handle
  8.     with open(file_path) as file_handle:
  9.         # This assumes the the first line of the csv
  10.         # is a row containing the headers (Name,Time,Status
  11.         reader = csv.DictReader(file_handle, fieldnames=['Name', 'Time', 'Status'])
  12.         for row in reader:
  13.             if row['Status'].strip() == 'CONFIRMED':
  14.                 reservation_info.append((row['Time'].strip(), row['Name'].strip()))
  15.     # If the individual element of a list is a tuple, sorted will by default sort by comparing the first element, and if they're equal comparing the next element and so on. 
  16.     # Time being a string here is perfectly fine for sorting and since it's the first element, will be given higher priority
  17.     # We use the f-string and the generator expression in conjunction with join to generate the final output
  18.     return '\n'.join(f'{i[0]}, {i[1]}' for i in sorted(reservation_info))
  19.  
  20.  

Https://docs.python.org/3.6/library/...csv.DictReader
对于csv.DictReader上的文档
Https://docs.python.org/3/tutorial/i...tring-literals
有关f弦的文档
Https://docs.python.org/3/reference/...or-expressions
有关生成器表达式的文档
Https://www.python.org/dev/peps/pep-0343/
->With语句上的PEP 343

# 回答2


2的代码没有问题,但输出顺序与OP要求的不同。
18号线。

选择 | 换行 | 行号
  1.     return '\n'.join(f'{i[1]}, {i[0]}' for i in sorted(reservation_info))

标签: python

添加新评论