python字典大小函數(shù),python 函數(shù) 字典參數(shù)

Python字典中幾個常用函數(shù)總結(jié)

1、get() 返回指定鍵的值,如果值不在字典中返回default值。

站在用戶的角度思考問題,與客戶深入溝通,找到奉化網(wǎng)站設(shè)計與奉化網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗,讓設(shè)計與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:成都網(wǎng)站設(shè)計、網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣、國際域名空間、虛擬主機、企業(yè)郵箱。業(yè)務(wù)覆蓋奉化地區(qū)。

語法:dict.get(key,default=None)

參數(shù):

key 字典中要查找的鍵。

default 如果指定鍵的值不存在時,返回該默認值值。

例:

dict={'Name':'alex','Age':21}

print("Name is:%s"% dict.get('Name')+"\n"+ "Age is:%d"% dict.get('Age'))

顯示結(jié)果為:

Name is:alex

Age is:21

2、update() 將一個字典中的值更新到另一個字典中。

語法:dict.update(dict2)

參數(shù):

dict2 添加到指定字典dict里的字典。

例:

dict={'Name':'alex','Age':21}

dict2={'Sex':'female'}

dict.update(dict2)

print("Value is %s" % dict)

顯示結(jié)果為:

Value is {'Name': 'alex', 'Age': 21, 'Sex': 'female'}

求python 字典 中根據(jù)值的大小,按順序排列鍵的方法

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屬性,其中用到了匿名函數(shù)lambda, 參數(shù)為t列表,返回第二個元素t[1],也就是每個鍵值對中的value, ?從小到大排序時 reverse=False,從大到小排序是True!

Python中字典的內(nèi)建函數(shù)用法是什么?

點擊上方 "Python人工智能技術(shù)" 關(guān)注,星標或者置頂

22點24分準時推送,第一時間送達

后臺回復(fù)“大禮包”,送你特別福利

編輯:樂樂 | 來自:pypypypy

上一篇:

正文

大家好,我是Pythn人工智能技術(shù)。

內(nèi)置函數(shù)就是Python給你提供的,拿來直接用的函數(shù),比如print.,input等。

截止到python版本3.6.2 ,python一共提供了68個內(nèi)置函數(shù),具體如下

abs() dict() help() min() setattr()

all() dir() hex() next() slice()

any() divmod() id() object() sorted()

ascii() enumerate() input() oct() staticmethod()

bin() eval() int() open() str()

bool() exec() isinstance() ord() sum()

bytearray() ?lter() issubclass() pow() super()

bytes() ?oat() iter() print() tuple()

callable() format() len() property() type()

chr() frozenset() list() range() vars()

classmethod() getattr() locals() repr() zip()

compile() globals() map() reversed() __import__()

complex() hasattr() max() round()

delattr() hash() memoryview() set()

本文將這68個內(nèi)置函數(shù)綜合整理為12大類,正在學(xué)習(xí)Python基礎(chǔ)的讀者一定不要錯過,建議收藏學(xué)習(xí)!

和數(shù)字相關(guān) 1. 數(shù)據(jù)類型

bool : 布爾型(True,False)

int : 整型(整數(shù))

float : 浮點型(小數(shù))

complex : 復(fù)數(shù)

2. 進制轉(zhuǎn)換

bin() 將給的參數(shù)轉(zhuǎn)換成二進制

otc() 將給的參數(shù)轉(zhuǎn)換成八進制

hex() 將給的參數(shù)轉(zhuǎn)換成十六進制

print(bin(10)) # 二進制:0b1010

print(hex(10)) # 十六進制:0xa

print(oct(10)) # 八進制:0o12

3. 數(shù)學(xué)運算

abs() 返回絕對值

divmode() 返回商和余數(shù)

round() 四舍五入

pow(a, b) 求a的b次冪, 如果有三個參數(shù). 則求完次冪后對第三個數(shù)取余

sum() 求和

min() 求最小值

max() 求最大值

print(abs(-2)) # 絕對值:2

print(divmod(20,3)) # 求商和余數(shù):(6,2)

print(round(4.50)) # 五舍六入:4

print(round(4.51)) #5

print(pow(10,2,3)) # 如果給了第三個參數(shù). 表示最后取余:1

print(sum([1,2,3,4,5,6,7,8,9,10])) # 求和:55

print(min(5,3,9,12,7,2)) #求最小值:2

print(max(7,3,15,9,4,13)) #求最大值:15

和數(shù)據(jù)結(jié)構(gòu)相關(guān) 1. 序列

(1)列表和元組

list() 將一個可迭代對象轉(zhuǎn)換成列表

tuple() 將一個可迭代對象轉(zhuǎn)換成元組

print(list((1,2,3,4,5,6))) #[1, 2, 3, 4, 5, 6]

print(tuple([1,2,3,4,5,6])) #(1, 2, 3, 4, 5, 6)

(2)相關(guān)內(nèi)置函數(shù)

reversed() 將一個序列翻轉(zhuǎn), 返回翻轉(zhuǎn)序列的迭代器

slice() 列表的切片

lst = "你好啊"

it = reversed(lst) # 不會改變原列表. 返回一個迭代器, 設(shè)計上的一個規(guī)則

print(list(it)) #['啊', '好', '你']

lst = [1, 2, 3, 4, 5, 6, 7]

print(lst[1:3:1]) #[2,3]

s = slice(1, 3, 1) # 切片用的

print(lst[s]) #[2,3]

(3)字符串

str() 將數(shù)據(jù)轉(zhuǎn)化成字符串

print(str(123)+'456') #123456

format() 與具體數(shù)據(jù)相關(guān), 用于計算各種小數(shù), 精算等.

s = "hello world!"

print(format(s, "^20")) #劇中

print(format(s, "20")) #左對齊

print(format(s, "20")) #右對齊

# hello world!

# hello world!

# hello world!

print(format(3, 'b' )) # 二進制:11

print(format(97, 'c' )) # 轉(zhuǎn)換成unicode字符:a

print(format(11, 'd' )) # ?進制:11

print(format(11, 'o' )) # 八進制:13

print(format(11, 'x' )) # 十六進制(?寫字母):b

print(format(11, 'X' )) # 十六進制(大寫字母):B

print(format(11, 'n' )) # 和d?樣:11

print(format(11)) # 和d?樣:11

print(format(123456789, 'e' )) # 科學(xué)計數(shù)法. 默認保留6位小數(shù):1.234568e+08

print(format(123456789, '0.2e' )) # 科學(xué)計數(shù)法. 保留2位小數(shù)(小寫):1.23e+08

print(format(123456789, '0.2E' )) # 科學(xué)計數(shù)法. 保留2位小數(shù)(大寫):1.23E+08

print(format(1.23456789, 'f' )) # 小數(shù)點計數(shù)法. 保留6位小數(shù):1.234568

print(format(1.23456789, '0.2f' )) # 小數(shù)點計數(shù)法. 保留2位小數(shù):1.23

print(format(1.23456789, '0.10f')) # 小數(shù)點計數(shù)法. 保留10位小數(shù):1.2345678900

print(format(1.23456789e+3, 'F')) # 小數(shù)點計數(shù)法. 很大的時候輸出INF:1234.567890

bytes() 把字符串轉(zhuǎn)化成bytes類型

bs = bytes("今天吃飯了嗎", encoding="utf-8")

print(bs) #b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97'

bytearray() 返回一個新字節(jié)數(shù)組. 這個數(shù)字的元素是可變的, 并且每個元素的值得范圍是[0,256)

ret = bytearray("alex" ,encoding ='utf-8')

print(ret[0]) #97

print(ret) #bytearray(b'alex')

ret[0] = 65 #把65的位置A賦值給ret[0]

print(str(ret)) #bytearray(b'Alex')

ord() 輸入字符找?guī)ё址幋a的位置

chr() 輸入位置數(shù)字找出對應(yīng)的字符

ascii() 是ascii碼中的返回該值 不是就返回u

print(ord('a')) # 字母a在編碼表中的碼位:97

print(ord('中')) # '中'字在編碼表中的位置:20013

print(chr(65)) # 已知碼位,求字符是什么:A

print(chr(19999)) #丟

for i in range(65536): #打印出0到65535的字符

print(chr(i), end=" ")

print(ascii("@")) #'@'

repr() 返回一個對象的string形式

s = "今天\n吃了%s頓\t飯" % 3

print(s)#今天# 吃了3頓 飯

print(repr(s)) # 原樣輸出,過濾掉轉(zhuǎn)義字符 \n \t \r 不管百分號%

#'今天\n吃了3頓\t飯'

2. 數(shù)據(jù)集合

字典:dict 創(chuàng)建一個字典

集合:set 創(chuàng)建一個集合

frozenset() 創(chuàng)建一個凍結(jié)的集合,凍結(jié)的集合不能進行添加和刪除操作。

3. 相關(guān)內(nèi)置函數(shù)

len() 返回一個對象中的元素的個數(shù)

sorted() 對可迭代對象進行排序操作 (lamda)

語法:sorted(Iterable, key=函數(shù)(排序規(guī)則), reverse=False)

Iterable: 可迭代對象

key: 排序規(guī)則(排序函數(shù)), 在sorted內(nèi)部會將可迭代對象中的每一個元素傳遞給這個函數(shù)的參數(shù). 根據(jù)函數(shù)運算的結(jié)果進行排序

reverse: 是否是倒敘. True: 倒敘, False: 正序

lst = [5,7,6,12,1,13,9,18,5]

lst.sort() # sort是list里面的一個方法

print(lst) #[1, 5, 5, 6, 7, 9, 12, 13, 18]

ll = sorted(lst) # 內(nèi)置函數(shù). 返回給你一個新列表 新列表是被排序的

print(ll) #[1, 5, 5, 6, 7, 9, 12, 13, 18]

l2 = sorted(lst,reverse=True) #倒序

print(l2) #[18, 13, 12, 9, 7, 6, 5, 5, 1]

#根據(jù)字符串長度給列表排序

lst = ['one', 'two', 'three', 'four', 'five', 'six']

def f(s):

return len(s)

l1 = sorted(lst, key=f, )

print(l1) #['one', 'two', 'six', 'four', 'five', 'three']

enumerate() 獲取集合的枚舉對象

lst = ['one','two','three','four','five']

for index, el in enumerate(lst,1): # 把索引和元素一起獲取,索引默認從0開始. 可以更改

print(index)

print(el)

# 1

# one

# 2

# two

# 3

# three

# 4

# four

# 5

# five

all() 可迭代對象中全部是True, 結(jié)果才是True

any() 可迭代對象中有一個是True, 結(jié)果就是True

print(all([1,'hello',True,9])) #True

print(any([0,0,0,False,1,'good'])) #True

zip() 函數(shù)用于將可迭代的對象作為參數(shù), 將對象中對應(yīng)的元素打包成一個元組, 然后返回由這些元組組成的列表. 如果各個迭代器的元素個數(shù)不一致, 則返回列表長度與最短的對象相同

lst1 = [1, 2, 3, 4, 5, 6]

lst2 = ['醉鄉(xiāng)民謠', '驢得水', '放牛班的春天', '美麗人生', '辯護人', '被嫌棄的松子的一生']

lst3 = ['美國', '中國', '法國', '意大利', '韓國', '日本']

print(zip(lst1, lst1, lst3)) #

for el in zip(lst1, lst2, lst3):

print(el)

# (1, '醉鄉(xiāng)民謠', '美國')

# (2, '驢得水', '中國')

# (3, '放牛班的春天', '法國')

# (4, '美麗人生', '意大利')

# (5, '辯護人', '韓國')

# (6, '被嫌棄的松子的一生', '日本')

fiter() 過濾 (lamda)

語法:fiter(function. Iterable)

function: 用來篩選的函數(shù). 在?lter中會自動的把iterable中的元素傳遞給function. 然后根據(jù)function返回的True或者False來判斷是否保留留此項數(shù)據(jù) , Iterable: 可迭代對象

搜索公眾號頂級架構(gòu)師后臺回復(fù)“面試”,送你一份驚喜禮包。

def func(i): # 判斷奇數(shù)

return i % 2 == 1

lst = [1,2,3,4,5,6,7,8,9]

l1 = filter(func, lst) #l1是迭代器

print(l1) #

print(list(l1)) #[1, 3, 5, 7, 9]

map() 會根據(jù)提供的函數(shù)對指定序列列做映射(lamda)

語法 : map(function, iterable)

可以對可迭代對象中的每一個元素進行映射. 分別去執(zhí)行 function

def f(i): return i

lst = [1,2,3,4,5,6,7,]

it = map(f, lst) # 把可迭代對象中的每一個元素傳遞給前面的函數(shù)進行處理. 處理的結(jié)果會返回成迭代器print(list(it)) #[1, 2, 3, 4, 5, 6, 7]

和作用域相關(guān)

locals() 返回當前作用域中的名字

globals() 返回全局作用域中的名字

def func():

a = 10

print(locals()) # 當前作用域中的內(nèi)容

print(globals()) # 全局作用域中的內(nèi)容

print("今天內(nèi)容很多")

func()

# {'a': 10}

# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':

# _frozen_importlib_external.SourceFileLoader object at 0x0000026F8D566080,

# '__spec__': None, '__annotations__': {}, '__builtins__':

# (built-in), '__file__': 'D:/pycharm/練習(xí)/week03/new14.py', '__cached__': None,

# 'func': }

# 今天內(nèi)容很多

和迭代器生成器相關(guān)

range() 生成數(shù)據(jù)

next() 迭代器向下執(zhí)行一次, 內(nèi)部實際使?用了__ next__()?方法返回迭代器的下一個項目

iter() 獲取迭代器, 內(nèi)部實際使用的是__ iter__()?方法來獲取迭代器

for i in range(15,-1,-5):

print(i)

# 15

# 10

# 5

# 0

lst = [1,2,3,4,5]

it = iter(lst) # __iter__()獲得迭代器

print(it.__next__()) #1

print(next(it)) #2 __next__()

print(next(it)) #3

print(next(it)) #4

字符串類型代碼的執(zhí)行

eval() 執(zhí)行字符串類型的代碼. 并返回最終結(jié)果

exec() 執(zhí)行字符串類型的代碼

compile() 將字符串類型的代碼編碼. 代碼對象能夠通過exec語句來執(zhí)行或者eval()進行求值

s1 = input("請輸入a+b:") #輸入:8+9

print(eval(s1)) # 17 可以動態(tài)的執(zhí)行代碼. 代碼必須有返回值

s2 = "for i in range(5): print(i)"

a = exec(s2) # exec 執(zhí)行代碼不返回任何內(nèi)容

# 0

# 1

# 2

# 3

# 4

print(a) #None

# 動態(tài)執(zhí)行代碼

exec("""

def func():

print(" 我是周杰倫")

""" )

func() #我是周杰倫

code1 = "for i in range(3): print(i)"

com = compile(code1, "", mode="exec") # compile并不會執(zhí)行你的代碼.只是編譯

exec(com) # 執(zhí)行編譯的結(jié)果

# 0

# 1

# 2

code2 = "5+6+7"

com2 = compile(code2, "", mode="eval")

print(eval(com2)) # 18

code3 = "name = input('請輸入你的名字:')" #輸入:hello

com3 = compile(code3, "", mode="single")

exec(com3)

print(name) #hello

輸入輸出

print() : 打印輸出

input() : 獲取用戶輸出的內(nèi)容

print("hello", "world", sep="*", end="@") # sep:打印出的內(nèi)容用什么連接,end:以什么為結(jié)尾

#hello*world@

內(nèi)存相關(guān)

hash() : 獲取到對象的哈希值(int, str, bool, tuple). hash算法:(1) 目的是唯一性 (2) dict 查找效率非常高, hash表.用空間換的時間 比較耗費內(nèi)存

s = 'alex'print(hash(s)) #-168324845050430382lst = [1, 2, 3, 4, 5]print(hash(lst)) #報錯,列表是不可哈希的 id() : 獲取到對象的內(nèi)存地址s = 'alex'print(id(s)) #2278345368944

文件操作相關(guān)

open() : 用于打開一個文件, 創(chuàng)建一個文件句柄

f = open('file',mode='r',encoding='utf-8')

f.read()

f.close()

模塊相關(guān)

__ import__() : 用于動態(tài)加載類和函數(shù)

# 讓用戶輸入一個要導(dǎo)入的模塊

import os

name = input("請輸入你要導(dǎo)入的模塊:")

__import__(name) # 可以動態(tài)導(dǎo)入模塊

幫 助

help() : 函數(shù)用于查看函數(shù)或模塊用途的詳細說明

print(help(str)) #查看字符串的用途

調(diào)用相關(guān)

callable() : 用于檢查一個對象是否是可調(diào)用的. 如果返回True, object有可能調(diào)用失敗, 但如果返回False. 那調(diào)用絕對不會成功

a = 10

print(callable(a)) #False 變量a不能被調(diào)用

def f():

print("hello")

print(callable(f)) # True 函數(shù)是可以被調(diào)用的

查看內(nèi)置屬性

dir() : 查看對象的內(nèi)置屬性, 訪問的是對象中的__dir__()方法

print(dir(tuple)) #查看元組的方法

你還有什么想要補充的嗎?

免責(zé)聲明:本文內(nèi)容來源于網(wǎng)絡(luò),文章版權(quán)歸原作者所有,意在傳播相關(guān)技術(shù)知識行業(yè)趨勢,供大家學(xué)習(xí)交流,若涉及作品版權(quán)問題,請聯(lián)系刪除或授權(quán)事宜。

技術(shù)君個人微信

添加技術(shù)君個人微信即送一份驚喜大禮包

→ 技術(shù)資料共享

→ 技術(shù)交流社群

--END--

往日熱文:

Python程序員深度學(xué)習(xí)的“四大名著”:

這四本書著實很不錯!我們都知道現(xiàn)在機器學(xué)習(xí)、深度學(xué)習(xí)的資料太多了,面對海量資源,往往陷入到“無從下手”的困惑出境。而且并非所有的書籍都是優(yōu)質(zhì)資源,浪費大量的時間是得不償失的。給大家推薦這幾本好書并做簡單介紹。

獲得方式:

2.后臺回復(fù)關(guān)鍵詞:名著

Python 比較兩個字典大小

學(xué)習(xí) Python 時,遇到看到菜鳥教程里的 cmp() 方法,衍生出這篇文章。但是后來和朋友討論,感覺在實際應(yīng)用中極少有用到比較字典大小的場景。不過能搞懂一個知識點,還是很開心的。

cmp(dict1, dict2) 比較兩個字典大小的方法:先比字典長度,若相等就比 key 值,若再相等就比 value。

但是這個方法已經(jīng)被 Python 3 取消了。

請參考: Python2 用 cmp() 比較字典大小 , Python3 為什么取消了 __cmp__ 方法

operator 模塊提供了一系列方法比較兩個字典大小,詳細方法及使用示例請參考: Python3 使用 operator 模塊比較字典大小 。

但是在寫法上我們要注意,最好用 String 內(nèi)置的方法,這樣利于對空值的判斷:

結(jié)果如下:

python函數(shù)有哪些

1、print()函數(shù):打印字符串;

2、raw_input()函數(shù):從用戶鍵盤捕獲字符;

3、len()函數(shù):計算字符長度;

4、format()函數(shù):實現(xiàn)格式化輸出;

5、type()函數(shù):查詢對象的類型;

6、int()函數(shù)、float()函數(shù)、str()函數(shù)等:類型的轉(zhuǎn)化函數(shù);

7、id()函數(shù):獲取對象的內(nèi)存地址;

8、help()函數(shù):Python的幫助函數(shù);

9、s.islower()函數(shù):判斷字符小寫;

10、s.sppace()函數(shù):判斷是否為空格;

11、str.replace()函數(shù):替換字符;

12、import()函數(shù):引進庫;

13、math.sin()函數(shù):sin()函數(shù);

14、math.pow()函數(shù):計算次方函數(shù);

15、os.getcwd()函數(shù):獲取當前工作目錄;

16、listdir()函數(shù):顯示當前目錄下的文件;

17、time.sleep()函數(shù):停止一段時間;

18、random.randint()函數(shù):產(chǎn)生隨機數(shù);

19、range()函數(shù):返回一個列表,打印從1到100;

20、file.read()函數(shù):讀取文件返回字符串;

21、file.readlines()函數(shù):讀取文件返回列表;

22、file.readline()函數(shù):讀取一行文件并返回字符串;

23、split()函數(shù):用什么來間隔字符串;

24、isalnum()函數(shù):判斷是否為有效數(shù)字或字符;

25、isalpha()函數(shù):判斷是否全為字符;

26、isdigit()函數(shù):判斷是否全為數(shù)字;

27、 lower()函數(shù):將數(shù)據(jù)改成小寫;

28、upper()函數(shù):將數(shù)據(jù)改成大寫;

29、startswith(s)函數(shù):判斷字符串是否以s開始的;

30、endwith(s)函數(shù):判斷字符串是否以s結(jié)尾的;

31、file.write()函數(shù):寫入函數(shù);

32、file.writeline()函數(shù):寫入文件;

33、abs()函數(shù):得到某數(shù)的絕對值;

34、file.sort()函數(shù):對書數(shù)據(jù)排序;

35、tuple()函數(shù):創(chuàng)建一個元組;

36、find()函數(shù):查找 返回的是索引;

37、dict()函數(shù):創(chuàng)建字典;

38、clear()函數(shù):清楚字典中的所有項;

39、copy()函數(shù):復(fù)制一個字典,會修改所有的字典;

40、 get()函數(shù):查詢字典中的元素。

…………

分享名稱:python字典大小函數(shù),python 函數(shù) 字典參數(shù)
地址分享:http://muchs.cn/article8/phjoop.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、營銷型網(wǎng)站建設(shè)、做網(wǎng)站、虛擬主機用戶體驗、定制開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)