简体   繁体   English

使用键对嵌套列表进行排序的 Pythonic 方法

[英]Pythonic way to sort a nested list with keys

I have a list as follows:我有一个清单如下:

[{"1": {"movie": "0.53"}}, {"2": {"movie": "5.2"}}, {"3": {"movie": "3.2"}}]

And I know how to do t = sorted(new_list, key=lambda i: float(i['1']['movie']), reverse=True)我知道怎么做t = sorted(new_list, key=lambda i: float(i['1']['movie']), reverse=True)

but I am unsure on how can i also have the 1 , 2 , 3 as iteration ^但我不确定如何将123作为迭代 ^

What you could do is convert the inner dictionaries to a list from dict.values() , select the first value, then access the "movie" key.您可以做的是将内部字典从 dict.values dict.values()转换为列表, select 第一个值,然后访问"movie"键。 Then pass this as a float to the key function of sorted :然后将此作为float传递给sorted的键 function :

l = [{"1": {"movie": "0.53"}}, {"2": {"movie": "5.2"}}, {"3": {"movie": "3.2"}}]

result = sorted(l, key=lambda x: float(list(x.values())[0]["movie"]))

print(result)

Another option is to convert your list of dicts to a list of lists, sort the result from the resulting list dict.items() , then convert the result back to a list of dicts:另一种选择是将您的 dicts 列表转换为列表列表,从结果列表dict.items()中对结果进行排序,然后将结果转换回 dicts 列表:

l = [{"1": {"movie": "0.53"}}, {"2": {"movie": "5.2"}}, {"3": {"movie": "3.2"}}]

result = [
    dict(l)
    for l in sorted((list(d.items()) for d in l), key=lambda x: float(x[0][1]["movie"]))
]

print(result)

Which can also just use a basic dict.update approach to convert the list of dicts to a nested dict before sorting:也可以在排序之前使用基本的dict.update方法将字典列表转换为嵌套字典:

l = [{"1": {"movie": "0.53"}}, {"2": {"movie": "5.2"}}, {"3": {"movie": "3.2"}}]

dicts = {}
for d in l:
    dicts.update(d)
# {'1': {'movie': '0.53'}, '2': {'movie': '5.2'}, '3': {'movie': '3.2'}}

result = [{k: v} for k, v in sorted(dicts.items(), key=lambda x: float(x[1]["movie"]))]

print(result)

Or if we want to do it in one line, we can make use of collections.ChainMap :或者,如果我们想在一行中完成,我们可以使用collections.ChainMap

from collections import ChainMap

l = [{"1": {"movie": "0.53"}}, {"2": {"movie": "5.2"}}, {"3": {"movie": "3.2"}}]

result = [
    {k: v} for k, v in sorted(ChainMap(*l).items(), key=lambda x: float(x[1]["movie"]))
]

print(result)

Output: Output:

[{'1': {'movie': '0.53'}}, {'3': {'movie': '3.2'}}, {'2': {'movie': '5.2'}}]

Btw the list that you have posted is incorrect in syntax, assuming it to be list of dictionaries.顺便说一句,您发布的列表在语法上不正确,假设它是字典列表。 You can sort it like following:您可以按如下方式对其进行排序:

new_list = [
    {"1":{"movie": "0.53"}},
    {"2":{"movie": "5.2"}}, 
    {"3":{"movie": "3.2"}}
    ]

t = sorted(new_list, key=lambda x: float(list(x.items())[0][1]['movie']))

Output: Output:

[{'1': {'movie': '0.53'}}, {'3': {'movie': '3.2'}}, {'2': {'movie': '5.2'}}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM