簡體   English   中英

如何使用元組列表對壓縮字典進行排序?

[英]How sort a zipped dictionary with a tupled list?

我有一個字典,其中包含作為元組的項目,其中包含兩個元素:id 和秒(最后一個在列表中)。

我想對它進行排序,如果有任何元組的列表包含多個元素,則按照以秒為單位的順序(從最小到最大)將其與其 id 分開,如示例所示

代碼:

dictionary.items()

dict_items(
            [
            ('268 084 071', [36900]), 
            ('582 992 529', [43200]), 
            ('627 335 2770', [50400, 322800]), # tuple with id and a list of seconds
            ('171-451-814', [116600]), 
            ('537 430 002', [310200]), 
            ('366 342 588', [380900]), 
            ('994-4098-8201', [387200]), 
            ('981-2739-3075', [396200])
            ]
          )

預期的output:字典到有序列表,以秒為單位從最小到最大,並將列表中的元素與多個元素分開並將每個元素與其id分組

    [
        ('268 084 071', [36900]), 
        ('582 992 529', [43200]), 
        ('627 335 2770', [50400]), # was separated 
        ('171-451-814', [116600]), 
        ('537 430 002', [310200]), 
        ('627 335 2770', [322800]), # in here
        ('366 342 588', [380900]), 
        ('994-4098-8201', [387200]), 
        ('981-2739-3075', [396200])
    ]

由於重復的鍵,你不能用字典做你想做的事情,但這會創建一個包含分離數據的列表:

d = dict([('268 084 071', [36900]), 
          ('582 992 529', [43200]), 
          ('627 335 2770', [50400, 322800]), # tuple with id and a list of seconds
          ('171-451-814', [116600]), 
          ('537 430 002', [310200]), 
          ('366 342 588', [380900]), 
          ('994-4098-8201', [387200]), 
          ('981-2739-3075', [396200])])

lst = []
for key,values in d.items():
    for value in values:  # make values separate entries in the list
        lst.append((key,value))

lst.sort(key=lambda x:x[1]) # re-sort by value when done

for item in lst:
    print(item)

Output:

('268 084 071', 36900)
('582 992 529', 43200)
('627 335 2770', 50400)
('171-451-814', 116600)
('537 430 002', 310200)
('627 335 2770', 322800)
('366 342 588', 380900)
('994-4098-8201', 387200)
('981-2739-3075', 396200)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM