Python iterative sequence can sort summary

List sorted

Example: lst = [12, 6, 1, 3, 10]

Method One: Use the sort

def list_sort(lst):
    lst.sort()  # 就地排序,没有返回值
    return lst

Added: list.sort(key=None, reverse=False)You can specify whether the collation and descending

Note that only applies to sort the list, the sorting algorithm is used in the internal Timsort, one kind of insertion sort and merge sort algorithm binding

Method Two: Use sorted

def list_sort(lst):
    return sorted(lst)

NOTE: sorted(iterable, key, reverse)You can also specify whether the collation and descending

Note sorted using all iterables, it is create a new object, the original object unchanged


Dictionary sort

Sort by key


Method One: Use sorted and lambda
def dict_sort_by_key(dic):
    return dict(sorted(dic.items(), key=lambda x: x[0]))


Method two: dictionaries sorted using inferential
def dict_sort_by_key(dic):
    return {key:dic[key] for key in sorted(dic)}


Sort by value

Method One: Use sorted and lambda
def dict_sort_by_value(dic):
    return dict(sorted(dic.items(), key=lambda x: x[1]))


Method two: dictionaries sorted using inferential
def dict_sort_by_value(dic):
    # 使用字典的get方法的返回值作为排序规则
    return {key:dic[key] for key in sorted(dic, key=dic.get)}

Guess you like

Origin www.cnblogs.com/zzliu/p/10964413.html