关于python:按每个dicts键对dicts列表进行排序

Sort a list of dicts by each dicts key

我正在创建一个听写列表,然后我想按关键字的值(从低到高)对列表中的听写进行排序。

除此之外,一切正常:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def pythagorean(x1, y1, x2=0, y2=0):
    return ((x1 - x2)**2 + (y1 - y2)**2)**0.5


points = [(-2, -4), (0, -2), (-1, 0), (3, -5), (-2, -3), (3, 2)]

dicts = []

for coord in points:
    d = {}
    a1, b1 = coord
    distance = pythagorean(a1, b1)
    d[distance] = (a1, b1)
    dicts.append(d)

for i in dicts:
    print(i)

dist_list = []

for item in dicts:
    for key in item:
        dist_list.append(key)


temp = sorted(dicts, key=lambda d: [k in d for k in dist_list])
print(temp)

我得到以下输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
{4.47213595499958: (-2, -4)}
{2.0: (0, -2)}
{1.0: (-1, 0)}
{5.830951894845301: (3, -5)}
{3.605551275463989: (-2, -3)}
{3.605551275463989: (3, 2)}
[4.47213595499958, 2.0, 1.0, 5.830951894845301, 3.605551275463989, 3.605551275463989]
[{3.605551275463989: (-2, -3)},
 {3.605551275463989: (3, 2)},
 {5.830951894845301: (3, -5)},
 {1.0: (-1, 0)},
 {2.0: (0, -2)},
 {4.47213595499958: (-2, -4)}]

这种排序顺序是不正确的,至少就我认为应该如何排序而言是不正确的:按dict中键的值从低到高排序。


这是一种方法:

1
2
3
4
5
6
7
8
9
10
11
12
lst = [{3.605551275463989: (-2, -3)}, {3.605551275463989: (3, 2)},
       {5.830951894845301: (3, -5)}, {1.0: (-1, 0)},
       {2.0: (0, -2)}, {4.47213595499958: (-2, -4)}]

list(map(dict, sorted(list(i.items()) for i in lst)))

# [{1.0: (-1, 0)},
#  {2.0: (0, -2)},
#  {3.605551275463989: (-2, -3)},
#  {3.605551275463989: (3, 2)},
#  {4.47213595499958: (-2, -4)},
#  {5.830951894845301: (3, -5)}]

将每个dict中的键用作排序键可以将它们转换为列表:

1
2
3
4
5
6
7
>>> sorted(dicts, key=lambda d: list(d.keys()))
[{1.0: (-1, 0)},
 {2.0: (0, -2)},
 {3.605551275463989: (-2, -3)},
 {3.605551275463989: (3, 2)},
 {4.47213595499958: (-2, -4)},
 {5.830951894845301: (3, -5)}]