简体   繁体   English

如何使用元组列表对压缩字典进行排序?

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

I have a dictionary with items as tuples with two elements in it: id and seconds (this last one is inside a list).我有一个字典,其中包含作为元组的项目,其中包含两个元素:id 和秒(最后一个在列表中)。

I want to order it, in such a way that if there is any tuple that has a list with more than one element, separate it along with its id, according to an order in seconds (from least to greatest), as the example shows我想对它进行排序,如果有任何元组的列表包含多个元素,则按照以秒为单位的顺序(从最小到最大)将其与其 id 分开,如示例所示

Code:代码:

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])
            ]
          )

Expected output: dictionary to a ordered list, from smallest to largest in seconds, and separating the elements of the list with more than one element and grouping each element with its id预期的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])
    ]

You can't do what you want with a dictionary due to the duplicate keys, but this creates a list with the separated data:由于重复的键,你不能用字典做你想做的事情,但这会创建一个包含分离数据的列表:

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: 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