python sort和sorted

Transfer from https://www.jianshu.com/p/419a8732ac62

A function sort ()


  1. Sort () : only objects sorted list, change their order list, no return value, i.e., in situ ordering ;

  2. list.sort(key=None, reverse=False)

  • Key : setting sorting method, or list elements designated for sorting;
  • Reverse : l descending order, ascending order by default;
  1. One-dimensional list of sorted elements: Ignore parameter key
>>> a = ['TaoBao', 'Google', 'BaiDu']
>>> a.sort()
>>> a
['BaiDu', 'Google', 'TaoBao']
  1. dict composed list sorting
  • Parameter key acquisition dict key value or values are sorted
>>> a = [{'dell': 200}, {'mac': 100}]

# 字典的value排序
>>> a.sort(key=lambda x: list(x.values()))
>>> a
[{'mac': 100}, {'dell': 200}]

# 字典的key排序
>>> a.sort(key=lambda x: list(x.keys()))
>>> a
[{'dell': 200}, {'mac': 100}]

  • Press dict length sorted
>>> a = [{'mac': 200, 'huawei': 300, 'xiaomi': 150}, {'vivo': 210, 'Galaxy': 100}, {'Smartisan': 120, 'oppo': 200, 'lenovo': 50, 'meizu': 80}]
>>> a.sort(key=lambda x: len(x))
>>> a
[{'vivo': 210, 'Galaxy': 100}, {'mac': 200, 'huawei': 300, 'xiaomi': 150}, {'Smartisan': 120, 'oppo': 200, 'lenovo': 50, 'meizu': 80}]
  1. Multi-dimensional elements composed of sorted list
  • Press tuple of the 2 elements sorted
>>> a = [('mac', 3, 'b'), ('linux', 2, 'a'), ('mac', 1, 'c')]
>>> a
[('mac', 3, 'b'), ('linux', 2, 'a'), ('mac', 1, 'c')]
>>> a.sort(key=lambda x: x[1])    # lambda 函数:指定用于排序的元素
>>> a
[('mac', 1, 'c'), ('linux', 2, 'a'), ('mac', 3, 'b')]
  • Press tupel of the . 1 a and 3 are sorted elements
>>> a.sort(key=lambda x: (x[0], x[2]))
>>> a
[('linux', 2, 'a'), ('mac', 3, 'b'), ('mac', 1, 'c')]


二、sorted()


  1. sorted () : sort all iterables, the new object is returned after sorting, the original object remains the same;

  2. sorted(iterable [, key[, reverse]])

  • Key : setting sorting method, or the specified iteration object, the elements for sorting;
  • Reverse : l descending order, ascending order by default;
  1. One-dimensional element iteration of sorting objects
  • dict of key / value ordered: Back key / value consisting of the sorted list
# key排序
>>> a = {'Smartisan': 120, 'oppo': 200, 'lenovo': 50, 'meizu': 80}
>>> sorted(a)
['Smartisan', 'lenovo', 'meizu', 'oppo']

# value排序
>>> a = {'Smartisan': 120, 'oppo': 200, 'lenovo': 50, 'meizu': 80}
>>> sorted(a.values())
[50, 80, 120, 200]

  • dict of key / value ordered: RETURN sorted (key, value) composed of list
# 按字典的value排序
>>> a = {'Smartisan': 120, 'oppo': 200, 'lenovo': 50, 'meizu': 80}
>>> sorted(a.items(), key=lambda x: x[1])
[('lenovo', 50), ('meizu', 80), ('Smartisan', 120), ('oppo', 200)]
  • string Sort: Return characters list
>>> a = 'python'
>>> sorted(a)
['h', 'n', 'o', 'p', 't', 'y']
  • string split ordering
>>> a = "This is a test string from Andrew"
>>> sorted(a.split(), key=str.lower)    # split()函数进行字符串分割,key指定排序的方法
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
  1. Multi-dimensional ordering of elements
  • dict composition tuple or list sort: a method analogous to sort ()
>>> a = ({'dell': 200}, {'mac': 100})
>>> sorted(a, key=lambda x: list(x.values()))
[{'mac': 100}, {'dell': 200}]
  • tuple consisting tuple or list sort: a method analogous to sort ()
>>> a = (('mac', 3, 'b'), ('linux', 2, 'a'), ('mac', 1, 'c'))
>>> sorted(a, key=lambda x: (x[1], x[2]))    # 对tuple的第2、3个元素排序
[('mac', 1, 'c'), ('linux', 2, 'a'), ('mac', 3, 'b')]
  • list consisting tuple or list sort: a method analogous to sort ()
>>> a = [[1, 5, 9], [8, 4, 3], [4, 6, 2]]
>>> sorted(a, key=lambda x: x[0], reverse=True)    # 按第1个元素降序排列
[[8, 4, 3], [4, 6, 2], [1, 5, 9]]


Third, the difference between the sort () and sorted () and contact


  1. Sort () : acts only on the object list, no return value, modify the object itself;

  2. the sorted () : iterations acting on all objects, a new sort objects returned, does not modify the original object;

  3. sort () function does not need to copy the original list, less memory consumption, higher efficiency;

  4. sorted () function is powerful, range more widely used.

Four, Operator Module Functions

  1. Python provides a number of convenient functions, making access easier and faster method;

  2. Operator module is implemented in C language, the execution speed faster than the python code;

  3. Operator module itemgetter, attrgetter, methodcaller other common functions;

  4. You can use the function itemgetter () Alternatively sort function (sort, sorted) in the key parameter lambda function, more quickly and easily access elements;

  5. itemgetter () : returns a function, which function by acting on a target object, the target object position on the corresponding acquisition (index) elements, that implement the functions of elements taken.

>>> a = [1, 2, 100]
>>> from operator import itemgetter

# 获取位置为2的元素
>>> f = itemgetter(2)
>>> f
operator.itemgetter(2)
>>> f(a)
100

# 获取位置为1和2的元素
>>> f = itemgetter(1, 2)
>>> f
operator.itemgetter(1, 2)
>>> f(a)
(2, 100)

  1. Abstract understood that
    t is the target object, f = itemgetter (n)
    the call f (t), returns t [n], i.e. the position of the target object element n t of

  2. Use sort () or sorted () sorting, may be used itemgetter () alternate function key parameter lambda.

from operator import itemgetter

>>> a = [('mac', 3, 'b'), ('linux', 2, 'a'), ('mac', 1, 'c')]

>>> a.sort(key=itemgetter(1))
>>> a
[('mac', 1, 'c'), ('linux', 2, 'a'), ('mac', 3, 'b')]

>>> sorted(a, key=itemgetter(2))
[('linux', 2, 'a'), ('mac', 3, 'b'), ('mac', 1, 'c')]

Guess you like

Origin www.cnblogs.com/lzping/p/12601039.html