程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Lambda implementation for quick sorting of Python two-dimensional arrays

編輯:Python

sorted

sorted(__iterable,key,reverse), Can carry three parameters
1. Iteratable object
2. Sort of key
3. Ascending descending sequence

One dimensional array

# Without parameters , Default ascending order
>>>s = [5,3,4,1,2]
sorted(s)
[1, 2, 3, 4, 5]
# Add reverse=True, Descending order
sorted(s, reverse=True)
[5, 4, 3, 2, 1]

Arbitrary ordering of two-dimensional arrays

>>>s = [[4,5,6,'d'],[1,3,2,'a'],[6,7,8, 'b'], [9,3,2,'c']]
# sorted By default, the first value of the list element is arranged in ascending order
>>>sorted(s)
[[1, 3, 2, 'a'], [4, 5, 6, 'd'], [6, 7, 8, 'b'], [9, 3, 2, 'c']]
# reflection , If we want to compare the elements in the fourth column a,b,c,d Sort , One line of code teaches you to simply implement
>>>sorted(s, key=lambda x:x[3])
[[1, 3, 2, 'a'], [6, 7, 8, 'b'], [9, 3, 2, 'c'], [4, 5, 6, 'd']]
Empathy , I want to sort the second column
>>>sorted(s, key=lambda x:x[1])
[[1, 3, 2, 'a'], [9, 3, 2, 'c'], [4, 5, 6, 'd'], [6, 7, 8, 'b']]

Dictionary sort

# The default is to sort keys
>>>s = {'c':1,'b':2,'a':3}
>>>sorted(s)
['a', 'b', 'c']
# Yes value Arrange
>>>sorted(s.items(),key=lambda x:x[1], reverse=True)
[('a', 3), ('b', 2), ('c', 1)]

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved