當前位置:首頁 » 編程語言 » pythonsortvalue

pythonsortvalue

發布時間: 2022-06-07 19:45:38

python sort()用法

Python中的sort()方法用於數組排序,本文以實例形式對此加以詳細說明:
一、基本形式
列表有自己的sort方法,其對列表進行原址排序,既然是原址排序,那顯然元組不可能擁有這種方法,因為元組是不可修改的。

x = [4, 6, 2, 1, 7, 9]
x.sort()
print x # [1, 2, 4, 6, 7, 9]

如果需要一個排序好的副本,同時保持原有列表不變,怎麼實現呢

x =[4, 6, 2, 1, 7, 9]
y = x[ : ]
y.sort()
print y #[1, 2, 4, 6, 7, 9]
print x #[4, 6, 2, 1, 7, 9]

注意:y = x[:] 通過分片操作將列表x的元素全部拷貝給y,如果簡單的把x賦值給y:y = x,y和x還是指向同一個列表,並沒有產生新的副本。
另一種獲取已排序的列表副本的方法是使用sorted函數:

x =[4, 6, 2, 1, 7, 9]
y = sorted(x)
print y #[1, 2, 4, 6, 7, 9]
print x #[4, 6, 2, 1, 7, 9]

sorted返回一個有序的副本,並且類型總是列表,如下:

print sorted('Python') #['P', 'h', 'n', 'o', 't', 'y']

二、自定義比較函數
可以定義自己的比較函數,然後通過參數傳遞給sort方法:

def comp(x, y):
if x < y:
return 1
elif x > y:
return -1
else:
return 0

nums = [3, 2, 8 ,0 , 1]
nums.sort(comp)
print nums # 降序排序[8, 3, 2, 1, 0]
nums.sort(cmp) # 調用內建函數cmp ,升序排序
print nums # 降序排序[0, 1, 2, 3, 8]

三、可選參數
sort方法還有兩個可選參數:key和reverse

1、key在使用時必須提供一個排序過程總調用的函數:

x = ['mmm', 'mm', 'mm', 'm' ]
x.sort(key = len)
print x # ['m', 'mm', 'mm', 'mmm']

2、reverse實現降序排序,需要提供一個布爾值:

y = [3, 2, 8 ,0 , 1]
y.sort(reverse = True)
print y #[8, 3, 2, 1, 0]

以上是雲棲社區小編為您精心准備的的內容,在雲棲社區的博客、問答、公眾號、人物、課程等欄目也有的相關內容,歡迎繼續使用右上角搜索按鈕進行搜索python , 方法 sort python sort方法、python魔術方法詳解、python實例方法詳解、list.sort 使用方法、c list.sort 使用方法,以便於您獲取更多的相關知識。

⑵ python字典如何根據key比較value

1.sorted函數
首先介紹sorted函數,sorted(iterable,key,reverse),sorted一共有iterable,key,reverse這三個參數。
其中iterable表示可以迭代的對象,例如可以是dict.items()、dict.keys()等,key是一個函數,用來選取參與比較的元素,reverse則是用來指定排序是倒序還是順序,reverse=true則是倒序(從大到小),reverse=false則是順序(從小到大),默認是reverse=false。
2.按照key排序
要對字典按照key排序,可以直接調用sorted函數。
my_dict = {'lilee':25, 'age':24, 'phone':12}
sorted(my_dict.keys())
輸出結果為

['age', 'lilee', 'phone']

直接使用sorted(my_dict.keys())就能按key值對字典排序,這里是按照順序對key值進行排序的,如果想按照倒序排序的話,只需要將reverse置為true即可。
sorted(my_dcit.keys(), reverse = true)

3.按照value值排序
共有三種方法可以實現將字典按照value值進行排序
(1)key使用lambda匿名函數取value進行排序
d = {'lilee':25, 'wangyan':21, 'liqun':32, 'age':19}
sorted(d.items(), key=lambda item:item[1])
輸出結果為

[('age',19),('wangyan',21),('lilee',25),('liqun',32)]
如果需要倒序則

sorted(d.items(), key=lambda item:item[1], reverse=True)
得到的結果就會是

[('liqun',32),('lilee',25),('wangyan',21),('age',19)](2)使用operator的itemgetter進行排序
import operator
sorted(d.items(), key=operator.itemgetter(1))
輸出結果為
[('age',19),('wangyan',21),('lilee',25),('liqun',32)]

(3)將key和value分裝成元組,再進行排序
f = zip(d.keys(), d.values())
c = sorted(f)
輸出結果為
[('age',19),('wangyan',21),('lilee',25),('liqun',32)]

4.取出排序的前n個value值和key值
可以按照如下操作:
before = {"key1": 5,"key2": 6,"key3": 4,"key4": 3,
}# 排序after = dict(sorted(before.items(), key=lambda e: e[1]))print(after)
# 取出前幾個, 也可以在sorted返回的list中取前幾個
required_cnt = 2cnt = 0
for key, value in after.items():
cnt += 1if cnt > required_cnt:breakprint("{}:{}".format(key, value))

⑶ python字典怎麼排序

python字典怎麼排序?
定義一個字典類型
mydict = {2: '小路', 3: '黎明', 1: '郭富城', 4:'周董'}
可分別列印 key和value 看一下數據
按KEY排序,使用了 lambda和 reverse= False(正序)
key和value都輸出
reverse= True(逆序)
按value排序,漢字次序不是按拼音輸出
sorted並不改變字典本身的數據次序。
輸出後為列表和元組
可以 A = sorted(mydict.items(),key = lambda mydict:mydict[1],reverse= False) 賦值給A ,A的次序是變化後的
推薦:《Python教程》
注意事項
sorted並不改變字典本身的數據次序
如果要變化後的 可以賦值給另一個列表變數以上就是小編分享的關於python字典怎麼排序的詳細內容希望對大家有所幫助,更多有關python教程請關注環球青藤其它相關文章!

⑷ python中字典如何按照value值排序,並分別取出前n個value值和key值

before={
"key1":5,
"key2":6,
"key3":4,
"key4":3,
}
#排序
after=dict(sorted(before.items(),key=lambdae:e[1]))

print(after)

#取出前幾個,也可以在sorted返回的list中取前幾個
cnt=0
forkey,valueinafter.items():
cnt+=1
ifcnt>required_cnt:
break
print("{}:{}".format(key,value))

⑸ 按值排序Python字典問題,怎麼解決

下面的是按照value的值從大到小的順序來排序。
dic
=
{'a':31,
'bc':5,
'c':3,
'asd':4,
'aa':74,
'd':0}
dict=
sorted(dic.iteritems(),
key=lambda
d:d[1],
reverse
=
True)
print
dict
輸出的結果:
[('aa',
74),
('a',
31),
('bc',
5),
('asd',
4),
('c',
3),
('d',
0)]
下面我們分解下代碼
print
dic.iteritems()
得到[(鍵,值)]的列表。
然後用sorted方法,通過key這個參數,指定排序是按照value,也就是第一個元素d[1的值來排序。reverse
=
True表示是需要翻轉的,默認是從小到大,翻轉的話,那就是從大到小。

⑹ 通過價值Python字典排序問題,怎麼解決

下面的是按照value的值從大到小的順序來排序。

dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
print dict

輸出的結果:
[('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]

下面我們分解下代碼
print dic.iteritems() 得到[(鍵,值)]的列表。
然後用sorted方法,通過key這個參數,指定排序是按照value,也就是第一個元素d[1的值來排序。reverse = True表示是需要翻轉的,默認是從小到大,翻轉的話,那就是從大到小。

⑺ python怎麼對字典進行排序

python 字典(dict)的特點就是無序的,按照鍵(key)來提取相應值(value),如果我們需要字典按值排序的話,那可以用下面的方法來進行:

1 下面的是按照value的值從大到小的順序來排序。

dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
print dict

輸出的結果:
[('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]

下面我們分解下代碼
print dic.iteritems() 得到[(鍵,值)]的列表。
然後用sorted方法,通過key這個參數,指定排序是按照value,也就是第一個元素d[1的值來排序。reverse = True表示是需要翻轉的,默認是從小到大,翻轉的話,那就是從大到小。

2 對字典按鍵(key)排序:
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[0]) d[0]表示字典的鍵
print dict

⑻ Python對文本裡面的內容排序

把文本的格式貼出來看看

假設格式是:

5KB

100KB

1MB

3MB

9MB

2MB


可用下面的程序(python3)

units={"KB":1,"MB":1024}
defcalc(x):
forunit,amountinunits.items():
ifx.find(unit)>0:
number=int(x[:-2])
number*=amount
returnnumber

file=open("sort.txt","r")
values=list(file)
file.close()
values=[value[:-1]forvalueinvalues]
values.sort(key=calc)
print(values)
values=[value+" "forvalueinvalues]
file=open("sort.txt","w")
file.write("".join(values))
file.close()

⑼ 如何對列表進行排序 python

很多時候,我們需要對List進行排序,Python提供了兩個方法,對給定的List L進行排序:
方法1.用List的成員函數sort進行排序
方法2.用built-in函數sorted進行排序(從2.4開始)
這兩種方法使用起來差不多,以第一種為例進行講解:
從Python2.4開始,sort方法有了三個可選的參數,Python Library Reference里是這樣描述的

復制代碼代碼如下:

cmp:cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument:
"cmp=lambda x,y: cmp(x.lower(), y.lower())"
key:key specifies a function of one argument that is used to extract a comparison key from each list element: "key=str.lower"
reverse:reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.In general, the key and reverse conversion processes are much faster than specifying an
equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.

以下是sort的具體實例。
實例1:

復制代碼代碼如下:

>>>L = [2,3,1,4]
>>>L.sort()
>>>L
>>>[1,2,3,4]

實例2:

復制代碼代碼如下:

>>>L = [2,3,1,4]
>>>L.sort(reverse=True)
>>>L
>>>[4,3,2,1]

實例3:

復制代碼代碼如下:

>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>L.sort(cmp=lambda x,y:cmp(x[1],y[1]))
>>>L
>>>[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

實例4:

復制代碼代碼如下:

>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>L.sort(key=lambda x:x[1])
>>>L
>>>[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

實例5:

復制代碼代碼如下:

>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>import operator
>>>L.sort(key=operator.itemgetter(1))
>>>L
>>>[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

實例6:(DSU方法:Decorate-Sort-Undercorate)

復制代碼代碼如下:

>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>A = [(x[1],i,x) for i,x in enumerate(L)] #i can confirm the stable sort
>>>A.sort()
>>>L = [s[2] for s in A]
>>>L
>>>[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

以上給出了6中對List排序的方法,其中實例3.4.5.6能起到對以List item中的某一項
為比較關鍵字進行排序.
效率比較:

復制代碼代碼如下:

cmp < DSU < key

通過實驗比較,方法3比方法6要慢,方法6比方法4要慢,方法4和方法5基本相當
多關鍵字比較排序:
實例7:

復制代碼代碼如下:

>>>L = [('d',2),('a',4),('b',3),('c',2)]
>>> L.sort(key=lambda x:x[1])
>>> L
>>>[('d', 2), ('c', 2), ('b', 3), ('a', 4)]

我們看到,此時排序過的L是僅僅按照第二個關鍵字來排的,如果我們想用第二個關鍵字
排過序後再用第一個關鍵字進行排序呢?有兩種方法
實例8:

復制代碼代碼如下:

>>> L = [('d',2),('a',4),('b',3),('c',2)]
>>> L.sort(key=lambda x:(x[1],x[0]))
>>> L
>>>[('c', 2), ('d', 2), ('b', 3), ('a', 4)]

實例9:

復制代碼代碼如下:

>>> L = [('d',2),('a',4),('b',3),('c',2)]
>>> L.sort(key=operator.itemgetter(1,0))
>>> L
>>>[('c', 2), ('d', 2), ('b', 3), ('a', 4)]

為什麼實例8能夠工作呢?原因在於tuple是的比較從左到右之一比較的,比較完第一個,如果
相等,比較第二個

⑽ python字典有多個值的排序

s = {"a":"bb","b":"cc","c":"aa"}
def fun(s):
d = sorted(s.iteritems(),key=lambda t:t[1],reverse=False)
return d

d = fun(s)
print d
iteritems() 得到的[(鍵,值)]的列表, 通過sorted方法,指定排序的鍵值key是原來字典中的value屬性,其中用到了匿名函數lambda, 參數為t列表,返回第二個元素t[1],也就是每個鍵值對中的value, 從小到大排序時 reverse=False,從大到小排序是True!

熱點內容
高並發上傳 發布:2024-05-17 23:00:40 瀏覽:420
我的世界斗羅大陸伺服器網易手機 發布:2024-05-17 22:45:11 瀏覽:65
ideajar源碼 發布:2024-05-17 22:40:30 瀏覽:785
易語言取名源碼 發布:2024-05-17 22:40:12 瀏覽:645
存儲巴士x250 發布:2024-05-17 22:21:30 瀏覽:569
別墅中央空調地暖如何配置最好 發布:2024-05-17 22:20:09 瀏覽:930
php安裝mbstring 發布:2024-05-17 22:09:56 瀏覽:471
單向板中配置哪些鋼筋 發布:2024-05-17 22:09:16 瀏覽:798
winftp下載 發布:2024-05-17 21:51:33 瀏覽:694
壓縮板包裝 發布:2024-05-17 21:44:59 瀏覽:265