Python數據結構(字符串、列表、元組、字典、set集合)


1、一切皆對象

PyChram如何快速查找系統函數的源碼內容
注:系統函數的實現代碼查看builtins.py(包含列表、元組、字典)

對於Python,一切事物都是對象,對象基於類創建

所以,以下這些值都是對象: "wupeiqi"、38、['北京', '上海', '深圳'],並且是根據不同的類生成的對象。

(圖轉自大牛)

2、字符串

2.1 字符串概述

  在Python有各種各樣的string操作函數。在歷史上string類在python中經歷了一段輪回的歷史。在最開始的時候,python有一個 專門的string的module,要使用string的方法要先import,但后來由於眾多的python使用者的建議,從python2.0開始, string方法改為用S.method()的形式調用,只要S是一個字符串對象就可以這樣使用,而不用import。同時為了保持向后兼容,現在的 python中仍然保留了一個string的module,其中定義的方法與S.method()是相同的,這些方法都最后都指向了用S.method ()調用的函數。要注意,S.method()能調用的方法比string的module中的多,比如isdigit()、istitle()等就只能用 S.method()的方式調用。
  對一個字符串對象,首先想到的操作可能就是計算它有多少個字符組成,很容易想到用S.len(),但這是 錯的,應該是len(S)。因為len()是內置函數,包括在__builtin__模塊中。python不把len()包含在string類型中,乍看 起來好像有點不可理解,其實一切有其合理的邏輯在里頭。len()不僅可以計算字符串中的字符數,還可以計算list的成員數,tuple的成員數等等, 因此單單把len()算在string里是不合適,因此一是可以把len()作為通用函數,用重載實現對不同類型的操作,還有就是可以在每種有len() 運算的類型中都要包含一個len()函數。 python選擇的是第一種解決辦法。類似的還有str(arg)函數,它把arg用string類型表示出來。

2.2 字符串功能列表

class str(basestring):
    """
    str(object='') -> string
    
    Return a nice string representation of the object.
    If the argument is a string, the return value is the same object.
    """
    def capitalize(self):  
        """ 首字母變大寫 """
        """
        S.capitalize() -> string
        
        Return a copy of the string S with only its first character
        capitalized.
        """
        return ""

    def center(self, width, fillchar=None):  
        """ 內容居中,width:總長度;fillchar:空白處填充內容,默認無 """
        """
        S.center(width[, fillchar]) -> string
        
        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

    def count(self, sub, start=None, end=None):  
        """ 子序列個數 """
        """
        S.count(sub[, start[, end]]) -> int
        
        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are interpreted
        as in slice notation.
        """
        return 0

    def decode(self, encoding=None, errors=None):  
        """ 解碼 """
        """
        S.decode([encoding[,errors]]) -> object
        
        Decodes S using the codec registered for encoding. encoding defaults
        to the default encoding. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
        as well as any other name registered with codecs.register_error that is
        able to handle UnicodeDecodeErrors.
        """
        return object()

    def encode(self, encoding=None, errors=None):  
        """ 編碼,針對unicode """
        """
        S.encode([encoding[,errors]]) -> object
        
        Encodes S using the codec registered for encoding. encoding defaults
        to the default encoding. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that is able to handle UnicodeEncodeErrors.
        """
        return object()

    def endswith(self, suffix, start=None, end=None):  
        """ 是否以 xxx 結束 """
        """
        S.endswith(suffix[, start[, end]]) -> bool
        
        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False

    def expandtabs(self, tabsize=None):  
        """ 將tab轉換成空格,默認一個tab轉換成8個空格 """
        """
        S.expandtabs([tabsize]) -> string
        
        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""

    def find(self, sub, start=None, end=None):  
        """ 尋找子序列位置,如果沒找到,返回 -1 """
        """
        S.find(sub [,start [,end]]) -> int
        
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
        
        Return -1 on failure.
        """
        return 0

    def format(*args, **kwargs): # known special case of str.format
        """ 字符串格式化,動態參數,將函數式編程時細說 """
        """
        S.format(*args, **kwargs) -> string
        
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

    def index(self, sub, start=None, end=None):  
        """ 子序列位置,如果沒找到,報錯 """
        S.index(sub [,start [,end]]) -> int
        
        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0

    def isalnum(self):  
        """ 是否是字母和數字 """
        """
        S.isalnum() -> bool
        
        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False

    def isalpha(self):  
        """ 是否是字母 """
        """
        S.isalpha() -> bool
        
        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False

    def isdigit(self):  
        """ 是否是數字 """
        """
        S.isdigit() -> bool
        
        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False

    def islower(self):  
        """ 是否小寫 """
        """
        S.islower() -> bool
        
        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def isspace(self):  
        """
        S.isspace() -> bool
        
        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

    def istitle(self):  
        """
        S.istitle() -> bool
        
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. uppercase characters may only follow uncased
        characters and lowercase characters only cased ones. Return False
        otherwise.
        """
        return False

    def isupper(self):  
        """
        S.isupper() -> bool
        
        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def join(self, iterable):  
        """ 連接 """
        """
        S.join(iterable) -> string
        
        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""

    def ljust(self, width, fillchar=None):  
        """ 內容左對齊,右側填充 """
        """
        S.ljust(width[, fillchar]) -> string
        
        Return S left-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

    def lower(self):  
        """ 變小寫 """
        """
        S.lower() -> string
        
        Return a copy of the string S converted to lowercase.
        """
        return ""

    def lstrip(self, chars=None):  
        """ 移除左側空白 """
        """
        S.lstrip([chars]) -> string or unicode
        
        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def partition(self, sep):  
        """ 分割,前,中,后三部分 """
        """
        S.partition(sep) -> (head, sep, tail)
        
        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it.  If the separator is not
        found, return S and two empty strings.
        """
        pass

    def replace(self, old, new, count=None):  
        """ 替換 """
        """
        S.replace(old, new[, count]) -> string
        
        Return a copy of string S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""

    def rfind(self, sub, start=None, end=None):  
        """
        S.rfind(sub [,start [,end]]) -> int
        
        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
        
        Return -1 on failure.
        """
        return 0

    def rindex(self, sub, start=None, end=None):  
        """
        S.rindex(sub [,start [,end]]) -> int
        
        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0

    def rjust(self, width, fillchar=None):  
        """
        S.rjust(width[, fillchar]) -> string
        
        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

    def rpartition(self, sep):  
        """
        S.rpartition(sep) -> (head, sep, tail)
        
        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass

    def rsplit(self, sep=None, maxsplit=None):  
        """
        S.rsplit([sep [,maxsplit]]) -> list of strings
        
        Return a list of the words in the string S, using sep as the
        delimiter string, starting at the end of the string and working
        to the front.  If maxsplit is given, at most maxsplit splits are
        done. If sep is not specified or is None, any whitespace string
        is a separator.
        """
        return []

    def rstrip(self, chars=None):  
        """
        S.rstrip([chars]) -> string or unicode
        
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def split(self, sep=None, maxsplit=None):  
        """ 分割, maxsplit最多分割幾次 """
        """
        S.split([sep [,maxsplit]]) -> list of strings
        
        Return a list of the words in the string S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are removed
        from the result.
        """
        return []

    def splitlines(self, keepends=False):  
        """ 根據換行分割 """
        """
        S.splitlines(keepends=False) -> list of strings
        
        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []

    def startswith(self, prefix, start=None, end=None):  
        """ 是否起始 """
        """
        S.startswith(prefix[, start[, end]]) -> bool
        
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False

    def strip(self, chars=None):  
        """ 移除兩段空白 """
        """
        S.strip([chars]) -> string or unicode
        
        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def swapcase(self):  
        """ 大寫變小寫,小寫變大寫 """
        """
        S.swapcase() -> string
        
        Return a copy of the string S with uppercase characters
        converted to lowercase and vice versa.
        """
        return ""

    def title(self):  
        """
        S.title() -> string
        
        Return a titlecased version of S, i.e. words start with uppercase
        characters, all remaining cased characters have lowercase.
        """
        return ""

    def translate(self, table, deletechars=None):  
        """
        轉換,需要先做一個對應表,最后一個表示刪除字符集合
        intab = "aeiou"
        outtab = "12345"
        trantab = maketrans(intab, outtab)
        str = "this is string example....wow!!!"
        print str.translate(trantab, 'xm')
        """

        """
        S.translate(table [,deletechars]) -> string
        
        Return a copy of the string S, where all characters occurring
        in the optional argument deletechars are removed, and the
        remaining characters have been mapped through the given
        translation table, which must be a string of length 256 or None.
        If the table argument is None, no translation is applied and
        the operation simply removes the characters in deletechars.
        """
        return ""

    def upper(self):  
        """
        S.upper() -> string
        
        Return a copy of the string S converted to uppercase.
        """
        return ""

    def zfill(self, width):  
        """方法返回指定長度的字符串,原字符串右對齊,前面填充0。"""
        """
        S.zfill(width) -> string
        
        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width.  The string S is never truncated.
        """
        return ""

    def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
        pass

    def _formatter_parser(self, *args, **kwargs): # real signature unknown
        pass

    def __add__(self, y):  
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y):  
        """ x.__contains__(y) <==> y in x """
        pass

    def __eq__(self, y):  
        """ x.__eq__(y) <==> x==y """
        pass

    def __format__(self, format_spec):  
        """
        S.__format__(format_spec) -> string
        
        Return a formatted version of S as described by format_spec.
        """
        return ""

    def __getattribute__(self, name):  
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y):  
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass

    def __getslice__(self, i, j):  
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y):  
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y):  
        """ x.__gt__(y) <==> x>y """
        pass

    def __hash__(self):  
        """ x.__hash__() <==> hash(x) """
        pass

    def __init__(self, string=''): # known special case of str.__init__
        """
        str(object='') -> string
        
        Return a nice string representation of the object.
        If the argument is a string, the return value is the same object.
        # (copied from class doc)
        """
        pass

    def __len__(self):  
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y):  
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y):  
        """ x.__lt__(y) <==> x<y """
        pass

    def __mod__(self, y):  
        """ x.__mod__(y) <==> x%y """
        pass

    def __mul__(self, n):  
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more):  
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y):  
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self):  
        """ x.__repr__() <==> repr(x) """
        pass

    def __rmod__(self, y):  
        """ x.__rmod__(y) <==> y%x """
        pass

    def __rmul__(self, n):  
        """ x.__rmul__(n) <==> n*x """
        pass

    def __sizeof__(self):  
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __str__(self):  
        """ x.__str__() <==> str(x) """
        pass

str

str
字符串功能列表

2.3 應用案例

參考資料:http://www.runoob.com/python/python-strings.html

2.3.1 去空格及特殊符號

>>> a = " your are a boy. "
>>>
>>> a
' your are a boy. '
>>> a.strip()        # 兩邊去空格
'your are a boy.'
>>> a.lstrip()       # 右邊去空格
'your are a boy. '
>>> a.rstrip()       # 左邊去空格
' your are a boy.'    

2.3.2 字符串大小寫變換

格式:
S.lower()
S.upper()
S.swapcase()
S.capitalize()
S.title()

案例:
>>> str1 = "strcpy S" >>> str1.capitalize() # 首字母大寫 'Strcpy s' >>> str1.lower() # 所有字母小寫 'strcpy s' >>> str1.upper() # 所有字母大寫 'STRCPY S' >>> str1.title() # 只有首字母大寫,其余為小寫,模塊中沒有這個方法 'Strcpy S' >>> str1.swapcase() # 字母大小寫互換 'STRCPY s'

2.3.3 字符對齊

格式:
S.ljust(width,[fillchar])
S.rjust(width,[fillchar])
S.center(width, [fillchar])
S.zfill(width)

案例:
>>> str1 = "sdfsderwerafdsf" >>> str1.ljust(20) # 輸出width個字符,左對齊,不足部分用指定字符填充,默認的為空格 'sdfsderwerafdsf ' >>> str1.ljust(20,'-') # 指定填充字符 'sdfsderwerafdsf-----' >>> str1.rjust(20) # 同ljust,按照右對齊 ' sdfsderwerafdsf' >>> str1.rjust(20,'-') # 同ljust,按照右對齊,指定填充字符 '-----sdfsderwerafdsf' >>> str1.center(20,'-') # 中間對齊 '--sdfsderwerafdsf---' >>> str1.zfill(20) # 把指定字符串變成width長,並在右對齊,不足部分用0補足 '00000sdfsderwerafdsf'

2.3.4 字符串搜索和替換

格式:
S.find(substr, [start, [end]])    # 返回S中出現substr的第一個字母的標號,如果S中沒有substr則返回-1。start和end作用就相當於在S[start:end]中搜索
S.index(substr, [start, [end]])   # 與find()相同,只是在S中沒有substr時,會返回一個運行時錯誤 
S.rfind(substr, [start, [end]])   # 返回S中最后出現的substr的第一個字母的標號,如果S中沒有substr則返回-1,也就是說從右邊算起的第一次出現的substr的首字母標號
S.rindex(substr, [start, [end]])
S.count(substr, [start, [end]])   # 計算substr在S中出現的次數
S.replace(oldstr, newstr, [count])# 把S中的oldstar替換為newstr,count為替換次數。這是替換的通用形式,還有一些函數進行特殊字符的替換 
S.strip([chars])                  # 把S中前后chars中有的字符全部去掉,可以理解為把S前后chars替換為None 
S.lstrip([chars])
S.rstrip([chars])
S.expandtabs([tabsize])           # 把S中的tab字符替換沒空格,每個tab替換為tabsize個空格,默認是8個 

案例:
>>> str1 = "sdfsderwerafsdsf"
>>> str1.find("fs")
2
>>> str1.find("fs",4)
11
>>> str1.index("fs")
2
>>> str1.rfind("fs")
11
>>> str1.rindex("fs")
11
>>> str1.count("fs")
2
>>> str1.replace("fs","ab")
'sdabderweraabdsf'
>>> str1.replace("fs","ab",1)
'sdabderwerafsdsf'
>>> str1.strip("fs")         # 不是整體過濾fs字符,過濾f,s中兩個的任何一個,匹配字符串的前后的第一個字符
'dfsderwerafsd'
>>> str1.strip("f")
>>> str1.lstrip("f")
'sdfsderwerafsdsf'
>>> str1.rstrip("f")
'sdfsderwerafsds'

>>> str = "this is\tstring example....wow!!!";
>>>
>>> print("Original string: " + str)
Original string: this is        string example....wow!!!
>>> print("Defualt exapanded tab: " +  str.expandtabs())
Defualt exapanded tab: this is string example....wow!!!
>>> print("Double exapanded tab: " +  str.expandtabs(16))
Double exapanded tab: this is         string example....wow!!!
'sdfsderwerafsds'

2.3.5 字符串的分割和組合

S.split([sep, [maxsplit]])     # 以sep為分隔符,把S分成一個list。maxsplit表示分割的次數。默認的分割符為空白字符
S.rsplit([sep, [maxsplit]])
S.splitlines([keepends])       # 把S按照行分割符分為一個list,keepends是一個bool值,如果為真每行后而會保留行分割符。
S.join(seq)                    # join將容器對象拆分並以指定的字符將列表內的元素(element)連接起來,返回字符串(注:容器對象內的元素須為字符類型)

>>> str1 = "sdfsderwerafsdsf"
>>> str1.split("s")
['', 'df', 'derweraf', 'd', 'f']

>>> str1.split("s",1)
['', 'dfsderwerafsdsf']

# 案例1
>>> str1
'sdfsderwerafsdsf'
>>> str1.join("ccc")
'csdfsderwerafsdsfcsdfsderwerafsdsfc'


# 案例2
>>> a = ['no','pain','no','gain']
>>> '_ '.join(a)
'no_pain_no_gain'

# 容器對象內的元素須為字符類型
>>> b = ['I','am','no',1]
>>> '_'.join(b)

Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
'_'.join(b)
TypeError: sequence item 3: expected string, int found

# dict是以Key值作連接 dict的無序性,使元素隨機連接。set 同理
>>> L = {'p':'P','y':'Y','t':'T','h':'H','o':'O','n':'N'}
>>> '_'.join(L)
'h_o_n_p_t_y'

 

2.3.6 字符串的mapping

S.maketrans(from, to)           # 返回一個256個字符組成的翻譯表,其中from中的字符被一一對應地轉換成to,所以from和to必須是等長的。
S.translate(table[,deletechars])# 使用上面的函數產后的翻譯表,把S進行翻譯,並把deletechars中有的字符刪掉。需要注意的是,如果S為unicode字符串,那么就不支持 deletechars參數,可以使用把某個字符翻譯為None的方式實現相同的功能。此外還可以使用codecs模塊的功能來創建更加功能強大的翻譯表。

2.3.7 解碼與編碼

S.encode([encoding,[errors]]) # 以 encoding 指定的編碼格式編碼 string,如果出錯默認報一個ValueError 的異常,除非 errors 指定的是'ignore'或者'replace'
S.decode([encoding,[errors]]) # 字符串的測試函數,這一類函數在string模塊中沒有,這些函數返回的都是bool值

2.3.8 字符串的測試函數

格式:
S.startwith(prefix[,start[,end]]) # 是否以prefix開頭
S.endwith(suffix[,start[,end]])   # 以suffix結尾
S.isalnum() # 是否全是字母和數字,並至少有一個字符
S.isalpha() # 是否全是字母,並至少有一個字符
S.isdigit() # 是否全是數字,並至少有一個字符
S.isspace() # 是否全是空白字符,並至少有一個字符
S.islower() # S中的字母是否全是小寫
S.isupper() # S中的字母是否便是大寫
S.istitle() # S是否是首字母大寫的

注:這一類函數在string模塊中沒有,這些函數返回的都是bool值

案例:
>>> str1 = "sdfsderwerafsdsf"
>>> str1.startswith("s")
True
>>> str1.endswith("f")
True
>>> str1.endswith("c")
False
# 實際應用案例
# 案例1:根據后綴名判斷文件類型
filename = "ftp.exe"
if (filename.endswith(".exe")):
    print("這是一個exe執行文件")
else:
    print("這不是一個exe執行文件")

# 案例2:根據后綴名判斷文件是否為圖片
fileName1='pic.jpg'
# if fileName1.endswith('.gif') or fileName1.endswith('.jpg') or fileName1.endswith('.png'):
if fileName1.endswith((".gif", "jpg", ".png")):  # 與上一句等效
    print('這是一張圖片')
else:
    print('這不是一張圖片')


# 案例3:結合os模塊查找當前目錄下的某個類型的文件
import os
items = os.listdir(".")
newlist = []
for name in items:
    if name.endswith(".py"):
        newlist.append(name)
print(newlist)


>>> str1.isalnum()
True
>>> str1.isalpha()
True
>>> str1.isdigit()
False
>>> str1.isspace()
False
>>> str1.islower()
True
>>> str1.isupper()
False
>>> str1.istitle()
False:

2.3.9 漢語轉拼音

資料:http://pypinyin.readthedocs.io/en/latest/

應用案例:

pypinyin安裝:
pip install pypinyin

>>> from pypinyin import pinyin,lazy_pinyin
>>> import pypinyin
>>> a = "榪棟勝"
>>> lazy_pinyin(a)
['ma', 'dong', 'sheng']

注:
  再強調一次,字符串對象是不可改變的,也就是說在Python創建一個字符串后,你不能把這個字符中的某一部分改變。任何上面的函數改變了字符串后,都會返回一個新的字符串,原字串並沒有變。其實這也是有變通的辦法的,可以用S=list(S)這個函數把S變為由單個字符為成員的list,這樣的話就可以使用S[3]='a'的方式改變值,然后再使用S=" ".join(S)還原成字符串

2.4 字符串格式化

  目前Python字符串的格式化有兩種方法:百分號方式、format方式(百分號方式相對古老,format相對先進,目前兩者並存)

2.4.1 百分號方式

語法格式:%[(name)][flags][width].[precision]typecode

(name)      可選,用於選擇指定的key
flags         可選,可供選擇的值有:
    +         右對齊;正數前加正好,負數前加負號;
    -          左對齊;正數前無符號,負數前加負號;
    空格      右對齊;正數前加空格,負數前加負號;
    0          右對齊;正數前無符號,負數前加負號;用0填充空白處
width        可選,占有寬度
.precision  可選,小數點后保留的位數
typecode   必選
    s,獲取傳入對象的__str__方法的返回值,並將其格式化到指定位置
    r,獲取傳入對象的__repr__方法的返回值,並將其格式化到指定位置
    c,整數:將數字轉換成其unicode對應的值,10進制范圍為 0 <= i <= 1114111(py27則只支持0-255);字符:將字符添加到指定位置
    o,將整數轉換成 八  進制表示,並將其格式化到指定位置
    x,將整數轉換成十六進制表示,並將其格式化到指定位置
    d,將整數、浮點數轉換成 十 進制表示,並將其格式化到指定位置
    e,將整數、浮點數轉換成科學計數法,並將其格式化到指定位置(小寫e)
    E,將整數、浮點數轉換成科學計數法,並將其格式化到指定位置(大寫E)
    f, 將整數、浮點數轉換成浮點數表示,並將其格式化到指定位置(默認保留小數點后6位)
    F,同上
    g,自動調整將整數、浮點數轉換成 浮點型或科學計數法表示(超過6位數用科學計數法),並將其格式化到指定位置(如果是科學計數則是e;)
    G,自動調整將整數、浮點數轉換成 浮點型或科學計數法表示(超過6位數用科學計數法),並將其格式化到指定位置(如果是科學計數則是E;)
    %,當字符串中存在格式化標志時,需要用 %%表示一個百分號
注:Python中百分號格式化是不存在自動將整數轉換成二進制表示的方式

常用的格式化練習:

>>> st = "I am a %s!" % "teacher"
>>> print(st)
I am a teacher!
>>>
>>> st = "I am a %20s!" % "teacher"      # teacher 預留20個字符寬度,默認是右對齊
>>> print(st)
I am a              teacher!
>>>
>>> st = "I am a %+20s!" % "teacher"      # teacher 預留20個字符寬度,指定右對齊
>>> print(st)
I am a              teacher!
>>>
>>> st = "I am a %-20s!" % "teacher"      # teacher 預留20個字符寬度,指定左對齊
>>> print(st)
I am a teacher             !
>>>
>>> st = "I am %s age %d" % ("teacher", 18)                   # 接受不同的數據類型
>>> print(st)
I am teacher age 18
>>>
>>> st = "I am %(name)s age %(age)d" % {"name": "teacher", "age": 18}    # 使用變量傳遞參數
>>> print(st)
I am teacher age 18
>>>
>>> st = "percent %.2f" % 99.97623      # 保留兩位小數
>>> print(st)
percent 99.98
>>>
>>> st = "I am %(pp).2f" % {"pp": 123.425556, }  # 使用變量傳遞參數,保留兩位小
>>> print(st)
I am 123.43
>>>
>>> st = "I am %.2f %%" % 123.425556   # 注意%%
>>> print(st)
I am 123.43 %
>>>

2.4.2 format方式

[[fill]align][sign][#][0][width][,][.precision][type]

fill    【可選】空白處填充的字符
align   【可選】對齊方式(需配合width使用)
    <    內容左對齊
    >    內容右對齊(默認)
    =    內容右對齊,將符號放置在填充字符的左側,且只對數字類型有效。 即使:符號+填充物+數字
    ^    內容居中
sign    【可選】有無符號數字
    +     正號加正,負號加負;
    -     正號不變,負號加負;
    空格 正號空格,負號加負;
#       【可選】對於二進制、八進制、十六進制,如果加上#,會顯示 0b/0o/0x,否則不顯示
,      【可選】為數字添加分隔符,如:1,000,000
width   【可選】格式化位所占寬度
.precision 【可選】小數位保留精度
type       【可選】格式化類型
    傳入"字符串類型"的參數
        s,格式化字符串類型數據
        空白,未指定類型,則默認是None,同s
    傳入"整數類型"的參數
        b,將10進制整數自動轉換成2進制表示然后格式化
        c,將10進制整數自動轉換為其對應的unicode字符
        d,十進制整數
        o,將10進制整數自動轉換成8進制表示然后格式化;
        x,將10進制整數自動轉換成16進制表示然后格式化(小寫x)
        X,將10進制整數自動轉換成16進制表示然后格式化(大寫X)
    傳入"浮點型或小數類型"的參數
        e, 轉換為科學計數法(小寫e)表示,然后格式化;
        E, 轉換為科學計數法(大寫E)表示,然后格式化;
        f , 轉換為浮點型(默認小數點后保留6位)表示,然后格式化;
        F, 轉換為浮點型(默認小數點后保留6位)表示,然后格式化;
        g, 自動在e和f中切換
        G, 自動在E和F中切換
        %,顯示百分比(默認顯示小數點后6位)

>>> # 比百分號格式化功能強大的地方
... tpl = "I am {}, age {}, {}".format("seven", 29, "alex")
>>> print(tpl)
I am seven, age 29, alex
>>>
>>> tpl = "I am {}, age {}, {}".format(*["seven", 29, "alex", ])
>>> print(tpl)
I am seven, age 29, alex
>>>
>>> tpl = "I am {0}, age {1}, really {0}".format("seven", 29,)
>>> print(tpl)
I am seven, age 29, really seven
>>>
>>> tpl = "I am {0}, age {1}, really {0}".format(*["seven", 29, ])
>>> print(tpl)
I am seven, age 29, really seven
>>>
>>> tpl = "I am {name}, age {age}, really {name}".format(name="seven", age=29)
>>> print(tpl)
I am seven, age 29, really seven
>>>
>>> tpl = "I am {name}, age {age}, really {name}".format(**{"name": "seven", "ag
e": 29})
>>> print(tpl)
I am seven, age 29, really seven
>>>
>>> tpl = "I am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3, ], [11, 22,
33, ])
>>> print(tpl)
I am 1, age 2, really 3
>>>
>>> # 以下案例都開始指定接收參數的格式
...
>>> tpl = "I am {:s}, age {:d}, really {:f}".format("seven", 29, 922.002)
>>> print(tpl)
I am seven, age 29, really 922.002000
>>>
>>>
>>> tpl = "I am {:s}, age {:d}".format(*["seven", 29, ])
>>> print(tpl)
I am seven, age 29
>>>
>>> tpl = "I am {name:s}, age {age:d}".format(name="seven", age=29)
>>> print(tpl)
I am seven, age 29
>>>
>>> tpl = "I am {name:s}, age {age:d}".format(**{"name": "seven", "age": 29})
>>> print(tpl)
I am seven, age 29
>>>
>>> tpl = "numbers: 二進制:{:b}, 八進制:{:o}, 十進制:{:d}, 十六進制:{:x}, 十六進制:{:X}, 轉為百分比:{:%}".format(15, 15, 15, 15, 15, 15.123232, )
>>> print(tpl)
numbers: 二進制:1111, 八進制:17, 十進制:15, 十六進制:f, 十六進制:F, 轉為百分比:1512.323200%
>>>
>>> tpl = "numbers: 二進制:{0:b}, 八進制:{0:o}, 十進制:{0:d}, 十六進制:{0:x}, 十六進制:{0:X}, 轉為百分比:{0:%}".format(15)
>>> print(tpl)
numbers: 二進制:1111, 八進制:17, 十進制:15, 十六進制:f, 十六進制:F, 轉為百分比:1500.000000%
>>>
>>> tpl = "numbers: 二進制:{num:b}, 八進制:{num:o}, 十進制:{num:d}, 十六進制:{num:x}, 十六進制:{num:X}, 轉為百分比:{num:%}".format(num=15)
>>> print(tpl)
numbers: 二進制:1111, 八進制:17, 十進制:15, 十六進制:f, 十六進制:F, 轉為百分比:1500.000000%

2.4.3 format比百分號格式優勢

可以居中顯示
可以轉二進制
百分號區別
自定義填充字符

3、列表

官網文檔:http://python.usyiyi.cn/python_343/tutorial/datastructures.html#tuples-and-sequences

3.1 列表簡介

列表---->數組(其他語言)
可以存儲任何類型的其他內容,數字、字符串、字典等等
列組的索引由0開始

列表書寫建議
正常: li = [11,22,33,44]
建議: li = [11,22,33,44,]

列表常見操作:索引、切片、追加、刪除、長度、切片、循環、包含

Python 2.x
append(x):添加一個元素到列表的末尾。相當於a[len(a):] = [x]
count(x):返回列表中 x 出現的次數 精確查找不支持模糊查找
extend:將給定列表L中的所有元素附加到原列表a的末尾。相當於a[len(a):] = L 
index(x):返回列表中第一個值為 x 的元素的索引。如果沒有這樣的元素將會報錯
insert(x):在給定位置插入一個元素。第一個參數是准備插入到其前面的那個元素的索引,所以 a.insert(0, x) 在列表的最前面插入
pop(x):刪除列表中給定位置的元素並返回它。如果未指定索引,a.pop() 刪除並返回列表中的最后一個元素
remove(x):刪除列表中第一個值為 x 的元素。如果沒有這樣的元素將會報錯
reverse(x):反轉列表中的元素。相當於[::-1]
sort:原地排序列表中的元素

Python 3.x 新增
clear:刪除列表中所有的元素。相當於del a[:]
copy:返回列表的一個淺拷貝。等同於a[:]

>>> li = ['alex','eric','rain']
>>> li.reverse()                                     # 列表元素反向輸出
>>> li
['rain', 'eric', 'alex']

>>> li[::-1]
['Tony', 'alex', 'eric', 'rain']
>>> name_list = ['alex','65brother','tenglan']          # 初始化一個列表 >>> type(name_list)           # 確定類型 <type 'list'> >>> help(name_list)               # 獲取詳細幫助信息 >>> dir(name_list)                # 獲取簡單信息 [ .....省略,'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> name_list.append("xiaolan")            # 追加一個值 >>> name_list                # 查看追加結果 ['alex', '65brother', 'tenglan', 'xiaolan'] >>> name_list.insert(0,"xiaolan")             # 通過索引值插入內容 >>> name_list                # 查看追加結果 ['xiaolan', 'alex', '65brother', 'tenglan', 'xiaolan'] >>> name_list.count("xiaolan")             # 計算“xiaolei”值得總數 >>> name_list.index("65brother")             # 查看某個值得索引值 >>> name_list[2]            # 通過索引取值 '65brother' >>> name_list.remove("alex")          # 移除掃描到的第一個alex值 >>> name_list ['xiaolan', '65brother', 'tenglan', 'xiaolan']           # 查看移除結果 >>> name_list.pop()           # 移除最后一個值,並返回該值 'xiaolan' >>> name_list            # 查看移除效果 ['xiaolan', '65brother', 'tenglan'] '''extend''' >>> a [1, 2, 3, 4, 6, 'a', 'b'] >>> b = ['c','d',4,24,6] >>> a + b                           # 兩個列表合並 [1, 2, 3, 4, 6, 'a', 'b', 'c', 'd', 4, 24, 6] >>> a.extend(b) # 把b的內容擴展到a列表 >>> a [1, 2, 3, 4, 6, 'a', 'b', 'c', 'd', 4, 24, 6] >>> name = "Alex Li" >>> a.extend(name) # 把字符串的每個字母拆分擴展到a列表 >>> a [1, 2, 3, 4, 6, 'a', 'b', 'c', 'd', 4, 24, 6, 'A', 'l', 'e', 'x', ' ', 'L', 'i'] '''包含 ''' >>> a [1, 2, 3, 4, 6, 'a', 'b', 'c', 'd', 4, 24, 6, 'A', 'l', 'e', 'x', ' ', 'L', 'i'] >>> "A" in a # 字母A是否包含在列表a中 True >>> 24 in a # 數字24 是否包含在列表a中 True ''' 列表的各行打印''' >>> name_list = ['alex','65brother','tenglan'] >>> print(name_list[::2])               # [起始位置:結束位置:步長] ['alex', 'tenglan'] '''sort ''' sort Python 2.x(int,str按照ASCII排序) sort Python 3.x(int,str不能同時存在排序) ''' 切片''' name = ['alex','ccc',33,55] name[0] # 第一個 name[1] # 第二個 不知道列表中元素個數 如何取倒數第一個? name[-1] # 倒數第一個 name[0:2] # 一次取n個 取值 顧頭不顧尾 name # 取所有值 name[:] # 取所有值 列表可以不斷的切分 name[:6][2:5][0][1]
注:insert, remove 或者 sort之類的方法只修改列表而沒有返回值打印出來 -- 它們其實返回了默認值None
''' 深copy和淺copy 常見問題解答: 1)為什么要拷貝? 當進行修改時,想要保留原來的數據和修改后的數據 2)數字字符串和集合在修改時的差異?(深淺拷貝不同的終極原因) 在修改數據時: 數字字符串:在內存中新建一份數據 集合:修改內存中的同一份數據 3)對於集合,如何保留其修改前和修改后的數據? 在內存中拷貝一份 4)對於集合,如何拷貝其n層元素同時拷貝? 深拷貝 應用場景: 1)監控模板的copy應用 ''' ''' 淺copy案例 第一層copy 第二層copy ''' >>> name = ['alex',9,0,39,33,1245,'cc',34,'eeaaccdd',34,9,99,[8,"aa",9,20]] >>> name2 = name.copy() >>> name[0] = "Alex" >>> name[-1][0] = 88 >>> print(name) ['Alex', 9, 0, 39, 33, 1245, 'cc', 34, 'eeaaccdd', 34, 9, 99, [88, 'aa', 9, 20]] >>> print(name2) ['alex', 9, 0, 39, 33, 1245, 'cc', 34, 'eeaaccdd', 34, 9, 99, [88, 'aa', 9, 20]] ''' 深copy案例 第一層copy 第二層copy ''' >>> import copy >>> name = ['alex',9,0,39,33,1245,'cc',34,'eeaaccdd',34,9,99,[8,"aa",9,20]] >>> name2 = copy.deepcopy(name) >>> name[0] = "Alex" >>> name[-1][0] = 88 >>> print(name) ['Alex', 9, 0, 39, 33, 1245, 'cc', 34, 'eeaaccdd', 34, 9, 99, [88, 'aa', 9, 20]] >>> print(name2) ['alex', 9, 0, 39, 33, 1245, 'cc', 34, 'eeaaccdd', 34, 9, 99, [8, 'aa', 9, 20]]

 

3.2 列表應用場景

案例01:一千萬條數據,有100條重復數據,要求刪除這100條數據

>>> for count in range(name.count("some str")):
...     name.remove("some str")
...

案例02:將列表作為堆棧使用

  列表方法使得將列表當作堆棧非常容易,最先進入的元素最后一個取出(后進先出)。使用 append() 將元素添加到堆棧的頂部。使用不帶索引的 pop() 從堆棧的頂部取出元素

>>> a
[2, 5, 4, 3, 1]
>>> a.append(6)
>>> a.append(7)
>>> a
[2, 5, 4, 3, 1, 6, 7]
>>> a.pop()
7
>>> a.pop()
6
>>> a
[2, 5, 4, 3, 1]

案例03:將列表作為隊列使用

也可以將列表當作隊列使用,此時最先進入的元素第一個取出(先進先出);但是列表用作此目的效率不高。在列表的末尾添加和彈出元素非常快,但是在列表的開頭插入或彈出元素卻很慢 (因為所有的其他元素必須向左移一位)。
如果要實現一個隊列,可以使用 collections.deque,它設計的目的就是在兩端都能夠快速添加和彈出元素

>>> from collections import deque
>>> queue = deque([1,2,3,4])                # 一個隊列,左邊是頭,右邊是尾 先進先出 
>>> queue.append(5) 
>>> queue
deque([1, 2, 3, 4, 5])
>>> queue.append(6)
>>> queue
deque([1, 2, 3, 4, 5, 6])
>>> queue.popleft()
1
>>> queue
deque([2, 3, 4, 5, 6])

3.3 del語句

del函數  刪除內存中的值(適用范圍:列表,變量、元組、字典等等)

>>> name_list = ['alex','65brother','tenglan','zhangsan','lisi']
>>> del name_list[0]
>>> name_list
['65brother', 'tenglan', 'zhangsan', 'lisi']
>>> del name_list[2:3]                               # 清除子列表
>>> name_list
['65brother', 'tenglan', 'lisi']
>>> del name_list[:]                                  # 清空列表
>>> name_list
[]
>>> del name_list                                     # 清除變量
>>> name_list                    
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'name_list' is not defined                        

3.4 列表練習題

寫一個列表,列表中包含本組所有成員的名字
往中間位置插入兩個臨組成員的名稱
取出第3-8的人列表
刪除第7個人
把剛才加入的兩個臨組的人一次性刪除
把組長的名稱加上組長備注
要求隔一個人打印一個

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -- append object to end """
        pass

    def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -- extend list by appending elements from the iterable """
        pass

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        pass

    def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        pass

    def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
        """
        L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
        cmp(x, y) -> -1, 0, 1
        """
        pass

    def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x """
        pass

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __delslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__delslice__(i, j) <==> del x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __iadd__(self, y): # real signature unknown; restored from __doc__
        """ x.__iadd__(y) <==> x+=y """
        pass

    def __imul__(self, y): # real signature unknown; restored from __doc__
        """ x.__imul__(y) <==> x*=y """
        pass

    def __init__(self, seq=()): # known special case of list.__init__
        """
        list() -> new empty list
        list(iterable) -> new list initialized from iterable's items
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    def __mul__(self, n): # real signature unknown; restored from __doc__
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __reversed__(self): # real signature unknown; restored from __doc__
        """ L.__reversed__() -- return a reverse iterator over the list """
        pass

    def __rmul__(self, n): # real signature unknown; restored from __doc__
        """ x.__rmul__(n) <==> n*x """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
        """
        x.__setslice__(i, j, y) <==> x[i:j]=y
                   
                   Use  of negative indices is not supported.
        """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ L.__sizeof__() -- size of L in memory, in bytes """
        pass

    __hash__ = None

list
list Code

4、元組

4.1 元組介紹

元組由逗號分割的若干值組成,例如:

>>> t = 1,2,3,4,"acg"            # 不帶大括號括號也是可以的
>>> type(t)
<class 'tuple'>

>>> t = (1,2,3,4,"acg")
>>> type(t)
<class 'tuple'>

# 元組可以嵌套
>>> u = t,(1,3,4,5)
>>> u
((1, 2, 3, 4, 'acg'), (1, 3, 4, 5))
>>> type(u)
<class 'tuple'>

# 元組內容是不能改變的
>>> t[0] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

# 但是元組內包含可變的對象
>>> a = ([1,3,4],[2,34,3])
>>> type(a)
<class 'tuple'>
>>> a[0][0]=11
>>> a
([11, 3, 4], [2, 34, 3])

  元組在輸出時總是有括號的,以便於正確表達嵌套結構;在輸入時括號可有可無,不過括號經常都是必須的。不能給元組中單獨的一個元素賦值,不過可以創建包含可變對象(例如列表)的元組。
4.2 元組和列表區別

 元組的作用:元組能實現的功能列表都能實現,工作中使用元組多數是提醒他人這個是一個元組,無法更改內容

>>> t = (1,2,3,4,'a','list') >>> type(t) <class 'tuple'> >>> dir(t) [......省略, 'count', 'index']

元組互相轉換列表(實現了元組的修改)

元組-->列表
>>> t (1, 2, 3, 4, 'a', 'list') >>> list(t) [1, 2, 3, 4, 'a', 'list']

列表-->元組
>>> a
[1, 2, 3, 4, 6, 'a', 'b', 'c', 'd', 4, 24, 6, 'A', 'l', 'e', 'x', ' ', 'L', 'i']
>>> tuple(a)
(1, 2, 3, 4, 6, 'a', 'b', 'c', 'd', 4, 24, 6, 'A', 'l', 'e', 'x', ' ', 'L', 'i')
class tuple(object):
    """
    tuple() -> empty tuple
    tuple(iterable) -> tuple initialized from iterable's items
    
    If the argument is a tuple, the return value is the same object.
    """
    def count(self, value): # real signature unknown; restored from __doc__
        """ T.count(value) -> integer -- return number of occurrences of value """
        return 0

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        T.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass

    def __getslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __hash__(self): # real signature unknown; restored from __doc__
        """ x.__hash__() <==> hash(x) """
        pass

    def __init__(self, seq=()): # known special case of tuple.__init__
        """
        tuple() -> empty tuple
        tuple(iterable) -> tuple initialized from iterable's items
        
        If the argument is a tuple, the return value is the same object.
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    def __mul__(self, n): # real signature unknown; restored from __doc__
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __rmul__(self, n): # real signature unknown; restored from __doc__
        """ x.__rmul__(n) <==> n*x """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ T.__sizeof__() -- size of T in memory, in bytes """
        pass

tuple
View Code

5、字典

5.1 字典介紹

  與序列不同,序列由數字做索引,字典由鍵做索引,鍵可以是任意不可變類型;字符串和數字永遠可以拿來做鍵。如果元組只包含字符串、 數字或元組,它們可以用作鍵;如果元組直接或間接地包含任何可變對象,不能用作鍵。你不能用列表作為鍵,因為列表可以用索引、切片或者像 append() 和extend() 這樣的方法修改。
  理解字典的最佳方式是把它看做無序的 鍵:值  對集合,要求是鍵必須是唯一的(在同一個字典內)。一對大括號將創建一個空的字典: {}。大括號中由逗號分隔的 鍵:值 對將成為字典的初始值;打印字典時也是按照這種方式輸出。
  字典的主要操作是依據鍵來存取值。也可以通過 del 刪除 一個 鍵:值 對。如果你用一個已經存在的鍵存儲值,那么以前為該鍵分配的值就會被覆蓋。從一個不存在的鍵中讀取值會導致錯誤。
  list(d.keys())返回字典中所有鍵組成的列表,列表的順序是隨機的(如果你想它是有序的,就用sorted(d.keys())代替)。[2]要檢查某個鍵是否在字典中,可以使用 in 關鍵字。

Python 2.x
clear:清除字典中的所有元素 
copy:淺拷貝
fromkeys:從序列鍵和值設置為value來創建一個新的字典
get:如果該鍵在字典中存在,獲取對應的值;如果該鍵在字典中不存在,默認返回none,也可以設置一個默認的返回值
has_key:判斷key是否存在 Python 3.x已經廢棄 key in id_db 判斷即可
items:獲取字典中的鍵值對放在列表中,鍵值對作為已元組的形式作為列表中的元素
iteritems
iterkeys
itervalues
keys:獲取字典中的鍵 pop:刪除字典中鍵(key)所在的鍵值對 popitem:隨機刪除字典中的元素 setdefault:設置字典中鍵對應的初始值,如果鍵值都存在,則顯示的是原來的初始值,如果不存在,默認顯示none,不默認的話,可是設置一個初始值。 update:把第二個字典中的鍵值對更新到第一個字典中 values:獲取字典的值
viewitems
viewkeys
viewvalues

Python 3.x
clear:清除字典中的所有元素 copy:淺拷貝 fromkeys:從序列鍵和值設置為value來創建一個新的字典(有坑) get:如果該鍵在字典中存在,獲取對應的值;如果該鍵在字典中不存在,默認返回none,也可以設置一個默認的返回值 使用索引也能取值但是存在key不存在報錯問題 items:獲取字典中的鍵值對放在列表中,鍵值對作為已元組的形式作為列表中的元素(字典變列表 數據量很大會很耗時 不要使用) keys:獲取字典中的鍵 pop:刪除字典中鍵(key)所在的鍵值對 也可以使用del刪除字典元素 popitem:隨機刪除字典中的元素 setdefault:設置字典中鍵對應的初始值,如果鍵值都存在,則顯示的是原來的初始值,如果不存在,默認顯示none,不默認的話,可是設置一個初始值。 update:把第二個字典中的鍵值對更新到第一個字典中 key如果已經存在會覆蓋不會更新 values:獲取字典的值
class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    """

    def clear(self): # real signature unknown; restored from __doc__
        """ 清除內容 """
        """ D.clear() -> None.  Remove all items from D. """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ 淺拷貝 """
        """ D.copy() -> a shallow copy of D """
        pass

    @staticmethod # known case
    def fromkeys(S, v=None): # real signature unknown; restored from __doc__
        """
        dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
        v defaults to None.
        """
        pass

    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ 根據key獲取值,d是默認值 """
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass

    def has_key(self, k): # real signature unknown; restored from __doc__
        """ 是否有key """
        """ D.has_key(k) -> True if D has a key k, else False """
        return False

    def items(self): # real signature unknown; restored from __doc__
        """ 所有項的列表形式 """
        """ D.items() -> list of D's (key, value) pairs, as 2-tuples """
        return []

    def iteritems(self): # real signature unknown; restored from __doc__
        """ 項可迭代 """
        """ D.iteritems() -> an iterator over the (key, value) items of D """
        pass

    def iterkeys(self): # real signature unknown; restored from __doc__
        """ key可迭代 """
        """ D.iterkeys() -> an iterator over the keys of D """
        pass

    def itervalues(self): # real signature unknown; restored from __doc__
        """ value可迭代 """
        """ D.itervalues() -> an iterator over the values of D """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ 所有的key列表 """
        """ D.keys() -> list of D's keys """
        return []

    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """ 獲取並在字典中移除 """
        """
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
        """
        pass

    def popitem(self): # real signature unknown; restored from __doc__
        """ 獲取並在字典中移除 """
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
        """ 如果key不存在,則創建,如果存在,則返回已存在的值且不修改 """
        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass

    def update(self, E=None, **F): # known special case of dict.update
        """ 更新
            {'name':'alex', 'age': 18000}
            [('name','sbsbsb'),]
        """
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
        If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
        In either case, this is followed by: for k in F: D[k] = F[k]
        """
        pass

    def values(self): # real signature unknown; restored from __doc__
        """ 所有的值 """
        """ D.values() -> list of D's values """
        return []

    def viewitems(self): # real signature unknown; restored from __doc__
        """ 所有項,只是將內容保存至view對象中 """
        """ D.viewitems() -> a set-like object providing a view on D's items """
        pass

    def viewkeys(self): # real signature unknown; restored from __doc__
        """ D.viewkeys() -> a set-like object providing a view on D's keys """
        pass

    def viewvalues(self): # real signature unknown; restored from __doc__
        """ D.viewvalues() -> an object providing a view on D's values """
        pass

    def __cmp__(self, y): # real signature unknown; restored from __doc__
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __contains__(self, k): # real signature unknown; restored from __doc__
        """ D.__contains__(k) -> True if D has a key k, else False """
        return False

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object's
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = {}
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass

    __hash__ = None

dict
View Code

練習:元素分類
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],將所有大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中。
即:{'k1': 大於66 , 'k2': 小於66}

name = [11,22,33,44,55,66,77,88,99,90]
k1 = []
k2 = []
k = {"k1":k1,"k2":k2}
for i in name:
    if i > 66:
        k1.append(i)
    else:
        k2.append(i)
print(k)
View Code

5.2 字典遍歷技巧

# 字典遍歷時,鍵和對應的值通過使用items()方法可以同時得到。

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

# 序列中遍歷時,使用 enumerate() 函數可以同時得到索引和對應的值。

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

# 同時遍歷兩個或更多的序列,使用 zip() 函數可以成對讀取元素。

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

# 要反向遍歷一個序列,首先正向生成這個序列,然后調用 reversed() 函數。

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

# 按排序順序遍歷一個序列,請使用sorted()函數,返回一個新的排序的列表,同時保留源不變。

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear

# 若要在遍歷內部修改正在迭代的序列(例如復制某些元素),建議您首先制作副本。在序列上循環不會隱式地創建副本。切片表示法使這尤其方便:

>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
for k,v in id_db.items():  # 效率低 字典變列表 數據量很大會很耗時 
      print(k,v) 

for key in id_db:
    print(key)

for key in id_db:           # 效率高
    print(key,id_db[key])

6、運算符運算

這篇文章寫得很詳細了,用到的話直接參考:http://www.runoob.com/python/python-operators.html

常見應用場景

10 % 2  # 返回余數 應用一個表格通過判斷余數顯示不同的顏色

7、set集合

  set是一個無序且不重復的元素集合,集合中的元素不會重復且沒有順序。集合的基本用途包括成員測試和消除重復條目。集合對象還支持並集、 交集、 差和對稱差等數學運算。

# set創建
# 方法1:se = set()  調用類的__init__功能 內部執行for循環,循環元組內容添加到set集合
se = set()         
li = [11,22,11,22,]
s1 = set(li)
print("s1:",s1,type(s1))

# 方法2:se = {} 調用方法1實現
s1 = {11,22,}
print("s1:",s1,type(s1))
結果:
均是 s1: {11, 22} <class 'set'>

# add--添加元素
>>> set1 = set()
>>> set1.add("mads")
>>> set1
{'mads'}
>>> set1.add("mads")              # 元素不重復,多次添加只有一個
>>> set1
{'mads'}
>>> set1.add("cl")
>>> set1
{'cl', 'mads'}    

# clear--清空
>>> set1.clear()
>>> set1
set([])

# copy--拷貝(淺拷貝)
# difference--刪除當前set中的所有包含在 new set 里的元素
# symmetric_difference--差集,創建新對象 
s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.difference(s2)  # s1 中存在 s2中不存在 的元素
s3 = s2.difference(s1)  # s2 中存在 s1中不存在 的元素
s3 = s1.symmetric_difference(s2) # s1 中存在 s2中不存在 的元素 + s2 中存在 s1中不存在 的元素
print("s1:",s1)
print("s2:",s2)
print("s3:",s3)

# difference_update--刪除當前set中的所有包含在 new set 里的元素
s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.difference(s2)  # s1 中存在 s2中不存在 的元素
s1.difference_update(s2)
print("s1:",s1)
print("s2:",s2)
print("s3:",s3)

# symmetric_difference_update--差集,改變原來 
s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.symmetric_difference(s2) # s1 中存在 s2中不存在 的元素 + s2 中存在 s1中不存在 的元素
s1.symmetric_difference_update(s2)
print("s1:",s1)
print("s2:",s2)
print("s3:",s3)

# discard--移除元素不存在也不報錯,移除成功與否都無返回值
# 元素存在,正常移除
s1 = {11,22,33}
s1.discard(11)
print(s1)
結果:
{22,33}

# 元素不存在,不報錯
s1 = {11,22,33}
s1.discard(1111)
print(s1)
結果:
{11,22,33}


# pop--隨機移除元素,並返回移除元素值,並非最后一個元素(set集合都事無序的)
s1 = {11,22,33,332,123,9,120,2824,12}
res = s1.pop()
print(s1,type(s1))
print(res)
結果:
{2824, 9, 11, 12, 332, 22, 120, 123} <class 'set'>
33

# remove--移除指定的元素
>>> set1
{'mads', 'lyl'}
>>> set1.remove('lyl')
>>> set1
set()

# intersection--取交集,新創建一個set 
s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.intersection(s2) # 取差集
s4 = s2.intersection(s1) # 同上沒有差異,等效
print("s1:",s1)
print("s2:",s2)
print("s3:",s3)
print("s4:",s4)
結果:
s1: {33, 11, 22}
s2: {33, 44, 22}
s3: {33, 22}
s4: {33, 22}


# intersection_update--取交集,修改原來set
s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.intersection(s2) # 取差集
s1.intersection_update(s2)
print("s1:",s1)
print("s2:",s2)
print("s3:",s3)
結果:
s1: {33, 22}
s2: {33, 44, 22}
s3: {33, 22}

# issubset--是否是子集
# issuperset--是否是父集
s1 = {22,33}
s2 = {22,33,44}
res1 = s1.issubset(s2)    # 判斷s1是否是s2的子集
res2 = s1.issuperset(s2)  # 判斷s1是否是s2的父集

print("s1:",s1)
print("s2:",s2)
print("判斷s1是否是s2的子集:",res1)
print("判斷s1是否是s2的父集:",res2)
結果:
s1: {33, 22}
s2: {33, 44, 22}
判斷s1是否是s2的子集: True
判斷s1是否是s2的父集: False

# isdisjoint--如果沒有交集,返回true
# union--並集
s1 = {11,22,33}
s2 = {22,33,44}
res = s1.isdisjoint(s2)  # s1和s2是否有交集,沒有交集返回True,有交集返回False
s3 = s1.union(s2)
print("s1:",s1)
print("s2:",s2)
print("s3:",s3)
print(res)

# update--更新
s1 = {11,22,33}
s2 = {22,33,44}
s1.update(s2)     # 把s2更新到s1中,因為set集合是無序不重復的,會去掉s1和s2中重復的元素值
print("s1:",s1)
print("s2:",s2)
 結果:
s1: {33, 22, 11, 44}
s2: {33, 44, 22}
class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object
    
    Build an unordered collection of unique elements.
    """
    def add(self, *args, **kwargs): # real signature unknown
        """ 添加 """
        """
        Add an element to a set.
        
        This has no effect if the element is already present.
        """
        pass

    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. """
        pass

    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. """
        pass

    def difference(self, *args, **kwargs): # real signature unknown
        """
        Return the difference of two or more sets as a new set.
        
        (i.e. all elements that are in this set but not the others.)
        """
        pass

    def difference_update(self, *args, **kwargs): # real signature unknown
        """ 刪除當前set中的所有包含在 new set 里的元素 """
        """ Remove all elements of another set from this set. """
        pass

    def discard(self, *args, **kwargs): # real signature unknown
        """ 移除元素 """
        """
        Remove an element from a set if it is a member.
        
        If the element is not a member, do nothing.
        """
        pass

    def intersection(self, *args, **kwargs): # real signature unknown
        """ 取交集,新創建一個set """
        """
        Return the intersection of two or more sets as a new set.
        
        (i.e. elements that are common to all of the sets.)
        """
        pass

    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ 取交集,修改原來set """
        """ Update a set with the intersection of itself and another. """
        pass

    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ 如果沒有交集,返回true  """
        """ Return True if two sets have a null intersection. """
        pass

    def issubset(self, *args, **kwargs): # real signature unknown
        """ 是否是子集 """
        """ Report whether another set contains this set. """
        pass

    def issuperset(self, *args, **kwargs): # real signature unknown
        """ 是否是父集 """
        """ Report whether this set contains another set. """
        pass

    def pop(self, *args, **kwargs): # real signature unknown
        """ 移除 """
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty.
        """
        pass

    def remove(self, *args, **kwargs): # real signature unknown
        """ 移除 """
        """
        Remove an element from a set; it must be a member.
        
        If the element is not a member, raise a KeyError.
        """
        pass

    def symmetric_difference(self, *args, **kwargs): # real signature unknown
        """ 差集,創建新對象"""
        """
        Return the symmetric difference of two sets as a new set.
        
        (i.e. all elements that are in exactly one of the sets.)
        """
        pass

    def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ 差集,改變原來 """
        """ Update a set with the symmetric difference of itself and another. """
        pass

    def union(self, *args, **kwargs): # real signature unknown
        """ 並集 """
        """
        Return the union of sets as a new set.
        
        (i.e. all elements that are in either set.)
        """
        pass

    def update(self, *args, **kwargs): # real signature unknown
        """ 更新 """
        """ Update a set with the union of itself and others. """
        pass

    def __and__(self, y): # real signature unknown; restored from __doc__
        """ x.__and__(y) <==> x&y """
        pass

    def __cmp__(self, y): # real signature unknown; restored from __doc__
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x. """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __iand__(self, y): # real signature unknown; restored from __doc__
        """ x.__iand__(y) <==> x&=y """
        pass

    def __init__(self, seq=()): # known special case of set.__init__
        """
        set() -> new empty set object
        set(iterable) -> new set object
        
        Build an unordered collection of unique elements.
        # (copied from class doc)
        """
        pass

    def __ior__(self, y): # real signature unknown; restored from __doc__
        """ x.__ior__(y) <==> x|=y """
        pass

    def __isub__(self, y): # real signature unknown; restored from __doc__
        """ x.__isub__(y) <==> x-=y """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __ixor__(self, y): # real signature unknown; restored from __doc__
        """ x.__ixor__(y) <==> x^=y """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __or__(self, y): # real signature unknown; restored from __doc__
        """ x.__or__(y) <==> x|y """
        pass

    def __rand__(self, y): # real signature unknown; restored from __doc__
        """ x.__rand__(y) <==> y&x """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __ror__(self, y): # real signature unknown; restored from __doc__
        """ x.__ror__(y) <==> y|x """
        pass

    def __rsub__(self, y): # real signature unknown; restored from __doc__
        """ x.__rsub__(y) <==> y-x """
        pass

    def __rxor__(self, y): # real signature unknown; restored from __doc__
        """ x.__rxor__(y) <==> y^x """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __sub__(self, y): # real signature unknown; restored from __doc__
        """ x.__sub__(y) <==> x-y """
        pass

    def __xor__(self, y): # real signature unknown; restored from __doc__
        """ x.__xor__(y) <==> x^y """
        pass

    __hash__ = None

set
View Code

應用案例:尋找差異

# 數據庫中原有
old_dict = {
    "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
    "#2":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
    "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
}
 
# cmdb 新匯報的數據
new_dict = {
    "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
    "#4":{ 'hostname':c2, 'cpu_count': 2, 'mem_capicity': 80 }
}

問題分析:
需要解決的事:
1)新增的數據要添加進去
2)已經有的數據要更新內容
3)刪除的信息要去掉
old_dict.keys()
new_dict.keys()
交集:即要更新的內容

8、collection模塊

8.1 collection模塊介紹(系統已經自帶)
  我們都知道,Python擁有一些內置的數據類型,比如str, int, list, tuple, dict等, collections模塊在這些內置數據類型的基礎上,提供了幾個額外的數據類型:
namedtuple(): 生成可以使用名字來訪問元素內容的tuple子類
deque: 雙端隊列,可以快速的從另外一側追加和推出對象
Counter: 計數器,主要用來計數
OrderedDict: 有序字典
defaultdict: 帶有默認值的字典

7.1.1 計數器(counter)

功能:是對字典類型的補充,用於追蹤值得出現次數 除了具備字典的所有的功能+自己的功能

>>> import  collections
>>> str1 = "adferwer" >>> obj = collections.Counter(str1) >>> print(obj) Counter({'r': 2, 'e': 2, 'w': 1, 'd': 1, 'a': 1, 'f': 1})

8.1.2 有序字典(OrderedDict)

 記錄了字典元素添加的順序

import  collections

#自己動手實現一個有序的字典
dict1 = {"aa":2,"bb":32,"cc":232}
#print(dict1)                   # 多次輸出查看結果是無序的
list1 = ["aa","bb","cc"]        # 序列有序的
for i in list1:                 # 多次執行結果輸出順序不變,即通過字典+列表實現了一個有序的字典
    print(i,dict1[i])

obj = collections.OrderedDict()    # 用collections實現有序字典
obj["aa"] = 2
obj["bb"] = 32
obj["cc"] = 232
print(obj)

8.1.3 默認字典

需求問題
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],將所有大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中。 即: {'k1': 大於66 , 'k2': 小於66}
name = [11,22,33,44,55,66,77,88,99,90]
k1 = []
k2 = []
k = {"k1":k1,"k2":k2}
for i in name:
    if i > 66:
        k1.append(i)
    else:
        k2.append(i)
print(k)
原生字典解決辦法
import  collections

name = [11,22,33,44,55,66,77,88,99,90]
obj = collections.defaultdict(list)
for i in name:
    if i >66:
        obj["k1"].append(i)
    else:
        obj["k2"].append(i)
print(obj)
使用collections默認字典解決辦法

8.1.4 可命名元組(namedtuple)

坐標應用

import collections

mydict = collections.namedtuple("mydict",["x","y","z"])
obj = mydict("111","222","333")
print(obj.x)
print(obj.y)
print(obj.z)
結果:111 222 333

8.1.5 雙向隊列(deque)

 一個線程安全的雙向隊列

import collections

d = collections.deque()
d.append("aa")
d.appendleft("cc")
d.appendleft("aa")
d.appendleft("bb")              # 從隊列左側插入
print(d)

r = d.count("aa")               # 元素數量統計
print(r)

d.extend(["dd","ff","gg"])      # 擴展
print(d)

index = d.index("aa")        # 元素位置,默認從左到右
print(index)

注:既然有雙向隊列,也有單項隊列(先進先出 FIFO )

import queue

q = queue.Queue()
q.put(1)                                   # 添加元素
print("queue size:",q.qsize())             # 單隊列大小
res = q.get(1)                             # 獲取元素
print(res)    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM