【问题标题】:I want to sort integers within the keys of a dictionary我想对字典键中的整数进行排序
【发布时间】:2018-10-26 17:44:25
【问题描述】:

我创建了一个接收餐厅预订信息的程序,但我想按时间对预订进行排序。

该函数将-txt.file 作为参数,文件的内容遵循此结构 - "name", "time", "status""status"CONFIRMEDCANCELLED)。它只应该显示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

【问题讨论】:

  • 抱歉,我们只能接受代码作为文本,而不是作为图像。不是每个人都可以阅读图像(他们可能在他们的位置被阻止,或者他们使用屏幕阅读器,或者是一个想要索引源代码的搜索引擎)。

标签: python python-3.x dictionary


【解决方案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

【讨论】:

  • @Pierre.Vriens 抱歉,是哪一部分?
  • @Pierre.Vriens 很好,除了复杂的 lambda 之外,我添加了 cmets 以供您理解,如果您难以理解循环和 dicts 的工作原理:)
  • 这是黄金。我现在明白了。太感谢了!这非常有帮助。我希望我的帖子易于理解,因为这是我第一次在 Stackoverflow 上发帖。谢谢。
  • @ChrisBanniq 我也是第一次,很高兴能帮上忙 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-27
  • 2011-12-11
  • 2016-04-17
  • 2012-03-19
  • 2013-07-27
相关资源
最近更新 更多