简体   繁体   English

在Python中对包含字典的列表列表进行排序

[英]Sort list of lists containing dictionaries in Python

I am trying to implement genetic algos to optimize pathways. 我正在尝试实施遗传算法来优化途径。 For that, I need to sort lists. 为此,我需要对列表进行排序。

The basic list (list_cities) looks like this: 基本列表(list_cities)如下所示:

[[{'city': 'Pau', 'lan': 43.293295, 'lng': -0.36357}, {'city': 'Marseille', 'lan': 43.293551, 'lng': 5.377397}, {'distance': 5572.500801706894}], [{'city': 'Nice', 'lan': 43.70168, 'lng': 7.260711}, {'city': 'Lyon', 'lan': 45.759132, 'lng': 4.834604}, {'distance': 6306.2650380290725}]]

As you can see, I have a global list, containing several lists (200) containing cities themselves and a distance (representing the total distance to link all the cities in the order of the list. I would like to sort my 200 city lists, by the last value which is the distance. I tried in many ways but without success. 正如您所看到的,我有一个全局列表,其中包含多个列表(200),其中包含城市本身和距离(表示按列表顺序链接所有城市的总距离。我想对我的200个城市列表进行排序,最后一个值就是距离。我尝试了很多方面但没有成功。

My last try : 我最后一次尝试:

sort_list = sorted(list_cities, key=lambda k: k['distance'])

Which give me the following result : 哪个给我以下结果:

TypeError: list indices must be integers or slices, not str TypeError:list indices必须是整数或切片,而不是str

The [[{},{}],[{},{}]] thing is a list of lists containing objects dicts (which I keep calling objects for the rest of this answer because the data is coming from JSON anyway). [[{},{}],[{},{}]]是一个包含 对象 dicts的列表列表(我继续为此答案的其余部分调用对象,因为无论如何数据来自JSON)。 So in order to sort the lists by a number contained by an inner object, you have to find the given object in the list, and then get the number from it. 因此,为了按内部对象包含的数字对列表进行排序,您必须在列表中找到给定的对象,然后从中获取数字。
As the example suggests and your comment confirms, the distance is always in the last element which you can access via index -1, and thus 如示例所示并且您的注释确认,距离始终位于您可以通过索引-1访问的最后一个元素中,因此

sort_list = sorted(list_cities, key=lambda k: k[-1]['distance'])

could work. 可以工作。

About the other question: I would feel it more natural to put only the cities in a list in an object: 关于另一个问题:我觉得将一个列表中的城市仅放入一个对象中会更自然:

[
 {
  'cities':[
   {'city':'Pau','lat':...,'lon':...},
   {<2nd city>},
   ...
   {<last city>}
  ],
  'distance':...
 },
 ...
]

then it would work with the original attempt. 然后它将适用于最初的尝试。
(Sorry about the clumsy example, I am typing it on touchscreen, uh) (抱歉笨拙的例子,我在触摸屏上打字,呃)

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

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