新聞中心
Python字典中幾個常用函數(shù)總結(jié)
1、get() 返回指定鍵的值,如果值不在字典中返回default值。
甘州網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),甘州網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為甘州近千家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)要多少錢,請找那個售后服務(wù)好的甘州做網(wǎng)站的公司定做!
語法:dict.get(key,default=None)
參數(shù):
key 字典中要查找的鍵。
default 如果指定鍵的值不存在時(shí),返回該默認(rèn)值值。
例:
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 字典調(diào)用C++函數(shù)
使用Python的ctypes,我們可以直接調(diào)用由C直接編譯出來的函數(shù)。其實(shí)就是調(diào)用動態(tài)鏈接庫中的函數(shù)。為什么我們需要這樣做呢,因?yàn)橛行r(shí)候,我們可能需要一個性能上比較講究的算法,有些時(shí)候,我們可以在Python中使用已經(jīng)有了的現(xiàn)成的被封閉在動態(tài)鏈接庫中的函數(shù)。下面是如何調(diào)用的示例。
首先,我們用一個乘法來表示一個算法功能。下面是C的程序:
int?multiply(int?num1,?int?num2){???
return?num1?*?num2;
}????
如果在Windows下,你可能需要寫成下面這個樣子:
#include?windows.h?
BOOL?APIENTRYDll
Main(HANDLE?hModule,?DWORD?dwReason,?LPVOID?lpReserved){????
return?TRUE;
}?
__declspec(dllexport)?
intmultiply(int?num1,?int?num2){?
return?num1?*?num2;
}????
然后,自然是把這個C文件編成動態(tài)鏈接庫:
Linux下的編譯:
gcc?-c?-fPIC?libtest.c
gcc?-shared?libtest.o?-o?libtest.so????
Windows下的編譯:
cl?-LD?libtest.c?-libtest.dll????
于是在我們的Python中可以這樣使用:
(其中的libtest.so在Windows下改成libtest.dll即可)
from?ctypes?import?*
import?os
libtest?=?cdll.LoadLibrary(os.getcwd()?+?'/libtest.so')
print?libtest.multiply(2,?2)4????
注意:上面的Python腳本中需要把動態(tài)鏈接庫放到當(dāng)前目錄中。
Python中字典的內(nèi)建函數(shù)用法是什么?
點(diǎn)擊上方 "Python人工智能技術(shù)" 關(guān)注,星標(biāo)或者置頂
22點(diǎn)24分準(zhǔn)時(shí)推送,第一時(shí)間送達(dá)
后臺回復(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 : 浮點(diǎn)型(小數(shù))
complex : 復(fù)數(shù)
2. 進(jìn)制轉(zhuǎn)換
bin() 將給的參數(shù)轉(zhuǎn)換成二進(jìn)制
otc() 將給的參數(shù)轉(zhuǎn)換成八進(jìn)制
hex() 將給的參數(shù)轉(zhuǎn)換成十六進(jìn)制
print(bin(10)) # 二進(jìn)制:0b1010
print(hex(10)) # 十六進(jìn)制:0xa
print(oct(10)) # 八進(jìn)制:0o12
3. 數(shù)學(xué)運(yùn)算
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è)計(jì)上的一個規(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), 用于計(jì)算各種小數(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' )) # 二進(jìn)制:11
print(format(97, 'c' )) # 轉(zhuǎn)換成unicode字符:a
print(format(11, 'd' )) # ?進(jìn)制:11
print(format(11, 'o' )) # 八進(jìn)制:13
print(format(11, 'x' )) # 十六進(jìn)制(?寫字母):b
print(format(11, 'X' )) # 十六進(jìn)制(大寫字母):B
print(format(11, 'n' )) # 和d?樣:11
print(format(11)) # 和d?樣:11
print(format(123456789, 'e' )) # 科學(xué)計(jì)數(shù)法. 默認(rèn)保留6位小數(shù):1.234568e+08
print(format(123456789, '0.2e' )) # 科學(xué)計(jì)數(shù)法. 保留2位小數(shù)(小寫):1.23e+08
print(format(123456789, '0.2E' )) # 科學(xué)計(jì)數(shù)法. 保留2位小數(shù)(大寫):1.23E+08
print(format(1.23456789, 'f' )) # 小數(shù)點(diǎn)計(jì)數(shù)法. 保留6位小數(shù):1.234568
print(format(1.23456789, '0.2f' )) # 小數(shù)點(diǎn)計(jì)數(shù)法. 保留2位小數(shù):1.23
print(format(1.23456789, '0.10f')) # 小數(shù)點(diǎn)計(jì)數(shù)法. 保留10位小數(shù):1.2345678900
print(format(1.23456789e+3, 'F')) # 小數(shù)點(diǎn)計(jì)數(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é)的集合不能進(jìn)行添加和刪除操作。
3. 相關(guān)內(nèi)置函數(shù)
len() 返回一個對象中的元素的個數(shù)
sorted() 對可迭代對象進(jìn)行排序操作 (lamda)
語法:sorted(Iterable, key=函數(shù)(排序規(guī)則), reverse=False)
Iterable: 可迭代對象
key: 排序規(guī)則(排序函數(shù)), 在sorted內(nèi)部會將可迭代對象中的每一個元素傳遞給這個函數(shù)的參數(shù). 根據(jù)函數(shù)運(yùn)算的結(jié)果進(jìn)行排序
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): # 把索引和元素一起獲取,索引默認(rèn)從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)民謠', '驢得水', '放牛班的春天', '美麗人生', '辯護(hù)人', '被嫌棄的松子的一生']
lst3 = ['美國', '中國', '法國', '意大利', '韓國', '日本']
print(zip(lst1, lst1, lst3)) #
for el in zip(lst1, lst2, lst3):
print(el)
# (1, '醉鄉(xiāng)民謠', '美國')
# (2, '驢得水', '中國')
# (3, '放牛班的春天', '法國')
# (4, '美麗人生', '意大利')
# (5, '辯護(hù)人', '韓國')
# (6, '被嫌棄的松子的一生', '日本')
fiter() 過濾 (lamda)
語法:fiter(function. Iterable)
function: 用來篩選的函數(shù). 在?lter中會自動的把iterable中的元素傳遞給function. 然后根據(jù)function返回的True或者False來判斷是否保留留此項(xiàng)數(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)
可以對可迭代對象中的每一個元素進(jìn)行映射. 分別去執(zhí)行 function
def f(i): return i
lst = [1,2,3,4,5,6,7,]
it = map(f, lst) # 把可迭代對象中的每一個元素傳遞給前面的函數(shù)進(jìn)行處理. 處理的結(jié)果會返回成迭代器print(list(it)) #[1, 2, 3, 4, 5, 6, 7]
和作用域相關(guān)
locals() 返回當(dāng)前作用域中的名字
globals() 返回全局作用域中的名字
def func():
a = 10
print(locals()) # 當(dāng)前作用域中的內(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)部實(shí)際使?用了__ next__()?方法返回迭代器的下一個項(xiàng)目
iter() 獲取迭代器, 內(nèi)部實(shí)際使用的是__ 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()進(jìn)行求值
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表.用空間換的時(shí)間 比較耗費(fèi)內(nèi)存
s = 'alex'print(hash(s)) #-168324845050430382lst = [1, 2, 3, 4, 5]print(hash(lst)) #報(bào)錯,列表是不可哈希的 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ù)或模塊用途的詳細(xì)說明
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)) #查看元組的方法
你還有什么想要補(bǔ)充的嗎?
免責(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í)的“四大名著”:
這四本書著實(shí)很不錯!我們都知道現(xiàn)在機(jī)器學(xué)習(xí)、深度學(xué)習(xí)的資料太多了,面對海量資源,往往陷入到“無從下手”的困惑出境。而且并非所有的書籍都是優(yōu)質(zhì)資源,浪費(fèi)大量的時(shí)間是得不償失的。給大家推薦這幾本好書并做簡單介紹。
獲得方式:
2.后臺回復(fù)關(guān)鍵詞:名著
python字典操作函數(shù)
字典是一種通過名字或者關(guān)鍵字引用的得數(shù)據(jù)結(jié)構(gòu),其鍵可以是數(shù)字、字符串、元組,這種結(jié)構(gòu)類型也稱之為映射。字典類型是Python中唯一內(nèi)建的映射類型,基本的操作包括如下:
(1)len():返回字典中鍵—值對的數(shù)量;
(2)d[k]:返回關(guān)鍵字對于的值;
(3)d[k]=v:將值關(guān)聯(lián)到鍵值k上;
(4)del d[k]:刪除鍵值為k的項(xiàng);
(5)key in d:鍵值key是否在d中,是返回True,否則返回False。
(6)clear函數(shù):清除字典中的所有項(xiàng)
(7)copy函數(shù):返回一個具有相同鍵值的新字典;deepcopy()函數(shù)使用深復(fù)制,復(fù)制其包含所有的值,這個方法可以解決由于副本修改而使原始字典也變化的問題
(8)fromkeys函數(shù):使用給定的鍵建立新的字典,鍵默認(rèn)對應(yīng)的值為None
(9)get函數(shù):訪問字典成員
(10)has_key函數(shù):檢查字典中是否含有給出的鍵
(11)items和iteritems函數(shù):items將所有的字典項(xiàng)以列表方式返回,列表中項(xiàng)來自(鍵,值),iteritems與items作用相似,但是返回的是一個迭代器對象而不是列表
(12)keys和iterkeys:keys將字典中的鍵以列表形式返回,iterkeys返回鍵的迭代器
(13)pop函數(shù):刪除字典中對應(yīng)的鍵
(14)popitem函數(shù):移出字典中的項(xiàng)
(15)setdefault函數(shù):類似于get方法,獲取與給定鍵相關(guān)聯(lián)的值,也可以在字典中不包含給定鍵的情況下設(shè)定相應(yīng)的鍵值
(16)update函數(shù):用一個字典更新另外一個字典
(17)?values和itervalues函數(shù):values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重復(fù)的元素
一、字典的創(chuàng)建
1.1 直接創(chuàng)建字典
d={'one':1,'two':2,'three':3}
printd
printd['two']
printd['three']
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
1.2 通過dict創(chuàng)建字典
# _*_ coding:utf-8 _*_
items=[('one',1),('two',2),('three',3),('four',4)]
printu'items中的內(nèi)容:'
printitems
printu'利用dict創(chuàng)建字典,輸出字典內(nèi)容:'
d=dict(items)
printd
printu'查詢字典中的內(nèi)容:'
printd['one']
printd['three']
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
items中的內(nèi)容:
[('one',1), ('two',2), ('three',3), ('four',4)]
利用dict創(chuàng)建字典,輸出字典內(nèi)容:
{'four':4,'three':3,'two':2,'one':1}
查詢字典中的內(nèi)容:
或者通過關(guān)鍵字創(chuàng)建字典
# _*_ coding:utf-8 _*_
d=dict(one=1,two=2,three=3)
printu'輸出字典內(nèi)容:'
printd
printu'查詢字典中的內(nèi)容:'
printd['one']
printd['three']
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
輸出字典內(nèi)容:
{'three':3,'two':2,'one':1}
查詢字典中的內(nèi)容:
二、字典的格式化字符串
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
printd
print"three is %(three)s."%d
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four':4,'three':3,'two':2,'one':1}
threeis3.
三、字典方法
3.1?clear函數(shù):清除字典中的所有項(xiàng)
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
printd
d.clear()
printd
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four':4,'three':3,'two':2,'one':1}
{}
請看下面兩個例子
3.1.1
# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
printdd
d={}
printd
printdd
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two':2,'one':1}
{}
{'two':2,'one':1}
3.1.2
# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
printdd
d.clear()
printd
printdd
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two':2,'one':1}
{}
{}
3.1.2與3.1.1唯一不同的是在對字典d的清空處理上,3.1.1將d關(guān)聯(lián)到一個新的空字典上,這種方式對字典dd是沒有影響的,所以在字典d被置空后,字典dd里面的值仍舊沒有變化。但是在3.1.2中clear方法清空字典d中的內(nèi)容,clear是一個原地操作的方法,使得d中的內(nèi)容全部被置空,這樣dd所指向的空間也被置空。
3.2?copy函數(shù):返回一個具有相同鍵值的新字典
# _*_ coding:utf-8 _*_
x={'one':1,'two':2,'three':3,'test':['a','b','c']}
printu'初始X字典:'
printx
printu'X復(fù)制到Y(jié):'
y=x.copy()
printu'Y字典:'
printy
y['three']=33
printu'修改Y中的值,觀察輸出:'
printy
printx
printu'刪除Y中的值,觀察輸出'
y['test'].remove('c')
printy
printx
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
初始X字典:
{'test': ['a','b','c'],'three':3,'two':2,'one':1}
X復(fù)制到Y(jié):
Y字典:
{'test': ['a','b','c'],'one':1,'three':3,'two':2}
修改Y中的值,觀察輸出:
{'test': ['a','b','c'],'one':1,'three':33,'two':2}
{'test': ['a','b','c'],'three':3,'two':2,'one':1}
刪除Y中的值,觀察輸出
{'test': ['a','b'],'one':1,'three':33,'two':2}
{'test': ['a','b'],'three':3,'two':2,'one':1}
注:在復(fù)制的副本中對值進(jìn)行替換后,對原來的字典不產(chǎn)生影響,但是如果修改了副本,原始的字典也會被修改。deepcopy函數(shù)使用深復(fù)制,復(fù)制其包含所有的值,這個方法可以解決由于副本修改而使原始字典也變化的問題。
# _*_ coding:utf-8 _*_
fromcopyimportdeepcopy
x={}
x['test']=['a','b','c','d']
y=x.copy()
z=deepcopy(x)
printu'輸出:'
printy
printz
printu'修改后輸出:'
x['test'].append('e')
printy
printz
運(yùn)算輸出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
輸出:
{'test': ['a','b','c','d']}
{'test': ['a','b','c','d']}
修改后輸出:
{'test': ['a','b','c','d','e']}
{'test': ['a','b','c','d']}
3.3?fromkeys函數(shù):使用給定的鍵建立新的字典,鍵默認(rèn)對應(yīng)的值為None
# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'])
printd
運(yùn)算輸出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':None,'two':None,'one':None}
或者指定默認(rèn)的對應(yīng)值
# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'],'unknow')
printd
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':'unknow','two':'unknow','one':'unknow'}
3.4?get函數(shù):訪問字典成員
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printd.get('one')
printd.get('four')
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
1
None
注:get函數(shù)可以訪問字典中不存在的鍵,當(dāng)該鍵不存在是返回None
3.5?has_key函數(shù):檢查字典中是否含有給出的鍵
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printd.has_key('one')
printd.has_key('four')
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
True
False
3.6?items和iteritems函數(shù):items將所有的字典項(xiàng)以列表方式返回,列表中項(xiàng)來自(鍵,值),iteritems與items作用相似,但是返回的是一個迭代器對象而不是列表
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
list=d.items()
forkey,valueinlist:
printkey,':',value
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
three :3
two :2
one :1
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
it=d.iteritems()
fork,vinit:
print"d[%s]="%k,v
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
d[three]=3
d[two]=2
d[one]=1
3.7?keys和iterkeys:keys將字典中的鍵以列表形式返回,iterkeys返回鍵的迭代器
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printu'keys方法:'
list=d.keys()
printlist
printu'\niterkeys方法:'
it=d.iterkeys()
forxinit:
printx
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
keys方法:
['three','two','one']
iterkeys方法:
three
two
one
3.8?pop函數(shù):刪除字典中對應(yīng)的鍵
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
d.pop('one')
printd
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
{'three':3,'two':2}
3.9?popitem函數(shù):移出字典中的項(xiàng)
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
d.popitem()
printd
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
{'two':2,'one':1}
3.10?setdefault函數(shù):類似于get方法,獲取與給定鍵相關(guān)聯(lián)的值,也可以在字典中不包含給定鍵的情況下設(shè)定相應(yīng)的鍵值
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printd.setdefault('one',1)
printd.setdefault('four',4)
printd
運(yùn)算結(jié)果:
{'three':3,'two':2,'one':1}
{'four':4,'three':3,'two':2,'one':1}
3.11?update函數(shù):用一個字典更新另外一個字典
# _*_ coding:utf-8 _*_
d={
'one':123,
'two':2,
'three':3
}
printd
x={'one':1}
d.update(x)
printd
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':123}
{'three':3,'two':2,'one':1}
3.12?values和itervalues函數(shù):values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重復(fù)的元素
# _*_ coding:utf-8 _*_
d={
'one':123,
'two':2,
'three':3,
'test':2
}
printd.values()
運(yùn)算結(jié)果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
[2,3,2,123]
python 列表內(nèi)有字典怎么使用
Python字典是另一種可變?nèi)萜髂P?,且可存儲任意類型對象,如字符串、?shù)字、元組等其他容器模型。
一、創(chuàng)建字典
字典由鍵和對應(yīng)值成對組成。字典也被稱作關(guān)聯(lián)數(shù)組或哈希表?;菊Z法如下:
復(fù)制代碼代碼如下:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
也可如此創(chuàng)建字典:
復(fù)制代碼代碼如下:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
注意:
每個鍵與值用冒號隔開(:),每對用逗號,每對用逗號分割,整體放在花括號中({})。
鍵必須獨(dú)一無二,但值則不必。
值可以取任何數(shù)據(jù)類型,但必須是不可變的,如字符串,數(shù)或元組。
二、訪問字典里的值
把相應(yīng)的鍵放入熟悉的方括弧,如下實(shí)例:
復(fù)制代碼代碼如下:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
#以上實(shí)例輸出結(jié)果:
#dict['Name']: Zara
#dict['Age']: 7
如果用字典里沒有的鍵訪問數(shù)據(jù),會輸出錯誤如下:
復(fù)制代碼代碼如下:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
#以上實(shí)例輸出結(jié)果:
#dict['Zara']:
#Traceback (most recent call last):
# File "test.py", line 4, in module
# print "dict['Alice']: ", dict['Alice'];
#KeyError: 'Alice'[/code]
三、修改字典
向字典添加新內(nèi)容的方法是增加新的鍵/值對,修改或刪除已有鍵/值對如下實(shí)例:
復(fù)制代碼代碼如下:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
#以上實(shí)例輸出結(jié)果:
#dict['Age']: 8
#dict['School']: DPS School
四、刪除字典元素
能刪單一的元素也能清空字典,清空只需一項(xiàng)操作。
顯示刪除一個字典用del命令,如下實(shí)例:
復(fù)制代碼代碼如下:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # 刪除鍵是'Name'的條目
dict.clear(); # 清空詞典所有條目
del dict ; # 刪除詞典
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
#但這會引發(fā)一個異常,因?yàn)橛胐el后字典不再存在:
dict['Age']:
#Traceback (most recent call last):
# File "test.py", line 8, in module
# print "dict['Age']: ", dict['Age'];
#TypeError: 'type' object is unsubscriptable
五、字典鍵的特性
字典值可以沒有限制地取任何python對象,既可以是標(biāo)準(zhǔn)的對象,也可以是用戶定義的,但鍵不行。
兩個重要的點(diǎn)需要記住:
1)不允許同一個鍵出現(xiàn)兩次。創(chuàng)建時(shí)如果同一個鍵被賦值兩次,后一個值會被記住,如下實(shí)例:
復(fù)制代碼代碼如下:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print "dict['Name']: ", dict['Name'];
#以上實(shí)例輸出結(jié)果:
#dict['Name']: Manni
2)鍵必須不可變,所以可以用數(shù),字符串或元組充當(dāng),所以用列表就不行,如下實(shí)例:
復(fù)制代碼代碼如下:
#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];
#以上實(shí)例輸出結(jié)果:
#Traceback (most recent call last):
# File "test.py", line 3, in module
# dict = {['Name']: 'Zara', 'Age': 7};
#TypeError: list objects are unhashable
六、字典內(nèi)置函數(shù)方法
Python字典包含了以下內(nèi)置函數(shù):
1、cmp(dict1, dict2):比較兩個字典元素。
2、len(dict):計(jì)算字典元素個數(shù),即鍵的總數(shù)。
3、str(dict):輸出字典可打印的字符串表示。
4、type(variable):返回輸入的變量類型,如果變量是字典就返回字典類型。
Python字典包含了以下內(nèi)置方法:
1、radiansdict.clear():刪除字典內(nèi)所有元素
2、radiansdict.copy():返回一個字典的淺復(fù)制
3、radiansdict.fromkeys():創(chuàng)建一個新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對應(yīng)的初始值
4、radiansdict.get(key, default=None):返回指定鍵的值,如果值不在字典中返回default值
5、radiansdict.has_key(key):如果鍵在字典dict里返回true,否則返回false
6、radiansdict.items():以列表返回可遍歷的(鍵, 值) 元組數(shù)組
7、radiansdict.keys():以列表返回一個字典所有的鍵
8、radiansdict.setdefault(key, default=None):和get()類似, 但如果鍵不已經(jīng)存在于字典中,將會添加鍵并將值設(shè)為default
9、radiansdict.update(dict2):把字典dict2的鍵/值對更新到dict里
10、radiansdict.values():以列表返回字典中的所有值
網(wǎng)站題目:python函數(shù)引用字典 python調(diào)用字典的函數(shù)
本文地址:http://fisionsoft.com.cn/article/doogsop.html