![](/img/trans.png)
[英]How to create sub-lists with 3 elements, but if a sub-list gets a single element then instead create two with 2 elements?
[英]Python . How to sort elements of sub-list if second elements are equal sort the sub-lists by first element
我有一個這樣的清單:
list_grade = [['m' , 7.5],['h',6.75],['z',15],['a',19.63],['b',6.75]]
我想要這個列表的確切輸出而不改變子列表的位置,但如果子列表的第二個元素相等,則按這兩個子列表的第一個元素對這兩個子列表進行排序。
我的預期輸出:
list_grade = [['m' , 7.5],['b',6.75],['z',15],['a',19.63],['h',6.75]]
例如 ['b',6.75] 和 ['h',6.75] 通過替換它們的索引來排序。
from collections import defaultdict
list_grade = [['m' , 7.5],['h',6.75],['z',15],['a',19.63],['b',6.75]]
# collect the elements by value, like
# {7.5: [['m', 7.5]], 6.75: [['h', 6.75], ['b', 6.75]], ...}
element_map = defaultdict(list)
for elem in list_grade:
element_map[elem[1]].append(elem)
# sort the elements
for k in element_map:
element_map[k].sort()
# rebuild the list
list_grade_sorted = [element_map[v].pop(0) for _,v in list_grade]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.