Python中的字典與成員運(yùn)算符初步探究
Python元字典
字典(dictionary)是除列表以外python之中最靈活的內(nèi)置數(shù)據(jù)結(jié)構(gòu)類型。列表是有序的對(duì)象結(jié)合,字典是無(wú)序的對(duì)象集合。
兩者之間的區(qū)別在于:字典當(dāng)中的元素是通過(guò)鍵來(lái)存取的,而不是通過(guò)偏移存取。
字典用"{ }"標(biāo)識(shí)。字典由索引(key)和它對(duì)應(yīng)的值value組成。
#!/usr/bin/python # -*- coding: UTF-8 -*- dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print dict['one'] # 輸出鍵為'one' 的值 print dict[2] # 輸出鍵為 2 的值 print tinydict # 輸出完整的字典 print tinydict.keys() # 輸出所有鍵 print tinydict.values() # 輸出所有值
輸出結(jié)果為:
This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john']
Python成員運(yùn)算符
除了以上的一些運(yùn)算符之外,Python還支持成員運(yùn)算符,測(cè)試實(shí)例中包含了一系列的成員,包括字符串,列表或元組。
以下實(shí)例演示了Python所有成員運(yùn)算符的操作:
#!/usr/bin/python a = 10 b = 20 list = [1, 2, 3, 4, 5 ]; if ( a in list ): print "Line 1 - a is available in the given list" else: print "Line 1 - a is not available in the given list" if ( b not in list ): print "Line 2 - b is not available in the given list" else: print "Line 2 - b is available in the given list" a = 2 if ( a in list ): print "Line 3 - a is available in the given list" else: print "Line 3 - a is not available in the given list"
以上實(shí)例輸出結(jié)果:
Line 1 - a is not available in the given list Line 2 - b is not available in the given list Line 3 - a is available in the given list
相關(guān)文章
Python易忽視知識(shí)點(diǎn)小結(jié)
這篇文章主要介紹了Python易忽視知識(shí)點(diǎn),實(shí)例分析了Python中容易被忽視的常見(jiàn)操作技巧,需要的朋友可以參考下2015-05-05Python入門(mén)教程(二十一)Python的數(shù)組
這篇文章主要介紹了Python入門(mén)教程(二十一)Python的數(shù)組,數(shù)組是一種特殊變量,數(shù)組可以在單個(gè)名稱下保存多個(gè)值,我們可以通過(guò)引用索引號(hào)來(lái)訪問(wèn)這些值,需要的朋友可以參考下2023-04-04Python深度學(xué)習(xí)pytorch神經(jīng)網(wǎng)絡(luò)Dropout應(yīng)用詳解解
這篇文章主要為大家介紹了Python深度學(xué)習(xí)中關(guān)于pytorch神經(jīng)網(wǎng)絡(luò)Dropout的應(yīng)用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-10-10Python Sphinx使用實(shí)例及問(wèn)題解決
這篇文章主要介紹了Python Sphinx使用實(shí)例及問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01Flask?+?MySQL如何實(shí)現(xiàn)用戶注冊(cè),登錄和登出的項(xiàng)目實(shí)踐
本文主要介紹了Flask?+?MySQL?如何實(shí)現(xiàn)用戶注冊(cè),登錄和登出的項(xiàng)目實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06