1、變量python
變量來源於數學,是計算機語言中能儲存計算結果或能表示值抽象概念。變量能夠經過變量名訪問。git
python中定義一個變量很是簡單web
name = 'web' age = 25
那麼調用name就會獲得字符串‘web’,調用age就會獲得數字25,能夠經過print來查看。其中name、age爲變量名,中間的 = 爲賦值符號,'web'、25爲變量值。編程
name, age = 'web', 25
變量的命名規則:api
1、變量名只能是大小寫字母、數字或下劃線的任意組合,不能以數字開頭。 二、不能使用python關鍵字做爲變量名:['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
三、變量要表詞達意,用英文單詞。
變量的定義方式:數組
駝峯體: AgeOfWeb = 25 下劃線: age_of_web = 25
其中駝峯體通常用於類的命名(面向對象),其餘如變量、函數、實例化對象都使用下劃線方式。app
常量:python中的變量均可以修改,約定俗成的方式,使用全大寫字母表示常量。less
PATH = r"D:\\test\\hello_world.py"
變量在內存的特殊機制:編程語言
i1 = 123456321 i2 = 123456321 # 至關於 i2 = i1 print(i1 is i2) s1 = 'asd123456zxc' s2 = 'asd123456zxc' # 至關於 s2 = s1 print(s1 is s2) l1 = [123] l2 = [123] # 兩個在不一樣內存 print(l1 is l2) d1 = {'age': 12} d2 = {'age': 12} # 兩個在不一樣內存 print(d1 is d2)
2、pthon基本數據類型ide
數字
數字分爲整型(int)和浮點型(float)
>>> age = 12 >>> height = 165.5 >>> type(age) #type():查看數據類型的方法 <class 'int'> >>> type(height) <class 'float'>
>>> 10+3 加 13 >>> 10-3 減 7 >>> 10*3 乘 30 >>> 10/3 除 3.3333333333333335 >>> 10//3 整除 3 >>> 10%3 取餘 1 >>> 2**3 n次方 8
布爾型
bool型只有兩個值:True和False
0,空字符串,空的列表、字典、元組、集合都爲False,其他都爲True
字符串
字符串是由數字、字母、下劃線組成的一串字符。它是編程語言中表示文本的數據類型。能夠用單引號或雙引號表示,也可用三引號進行換行表示。
string_example = "Hello World!"
exchange_line = """ Hello World!
"""
字符串是有序的,順序按索引定義,第一個字符索引爲0,日後依次遞增。用方括號取索引。
>>> s = 'Hello ' # 按索引取值,超過最大索引則報錯 >>> s[0] 'H' >>> s[4] 'o' >>> s[5] ' ' >>> s[6] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range # 查找某個字符的索引 >>> s.index('e') 1 # 字符串的長度 >>> len(s) 6 # 移除空白 >>> s1 = s.strip() >>> s1 'Hello' >>> s 'Hello ' #查找,存在返回1,不存在則返回-1 >>> s.find('e') 1 >>> s.find('i') -1
一、%拼接 >>> name, age = "web", 25 >>> "My name is %s, %s years old." % (name, age) 'My name is web, 25 years old.' 2、format拼接 >>> "My name is {}, {} years old.".format(name, age) 'My name is web, 25 years old.' >>> "My name is {0}, {1} years old.".format(name, age) 'My name is web, 25 years old.' >>> "My name is {1}, {0} years old.".format(name, age) 'My name is 25, web years old.' >>> "My name is {1}, {0} years old.".format(age, name) 'My name is web, 25 years old.' 三、 + 拼接(不推薦) >>> "My name is " + name + ", " + str(age) + " years old." 'My name is web, 25 years old.'
class str(object): """ str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. """ def capitalize(self): # real signature unknown; restored from __doc__ """ S.capitalize() -> str Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. """ return "" def casefold(self): # real signature unknown; restored from __doc__ """ S.casefold() -> str Return a version of S suitable for caseless comparisons. """ return "" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.center(width[, fillchar]) -> str 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): # real signature unknown; restored from __doc__ """ 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 encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__ """ S.encode(encoding='utf-8', errors='strict') -> bytes Encode S using the codec registered for encoding. Default encoding is 'utf-8'. 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 can handle UnicodeEncodeErrors. """ return b"" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ 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=8): # real signature unknown; restored from __doc__ """ S.expandtabs(tabsize=8) -> str 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): # real signature unknown; restored from __doc__ """ 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(self, *args, **kwargs): # known special case of str.format """ S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ pass def format_map(self, mapping): # real signature unknown; restored from __doc__ """ S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}'). """ return "" def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(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. Raises ValueError when the substring is not found. """ return 0 def isalnum(self): # real signature unknown; restored from __doc__ """ 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): # real signature unknown; restored from __doc__ """ 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 isdecimal(self): # real signature unknown; restored from __doc__ """ S.isdecimal() -> bool Return True if there are only decimal characters in S, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ 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 isidentifier(self): # real signature unknown; restored from __doc__ """ S.isidentifier() -> bool Return True if S is a valid identifier according to the language definition. Use keyword.iskeyword() to test for reserved identifiers such as "def" and "class". """ return False def islower(self): # real signature unknown; restored from __doc__ """ 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 isnumeric(self): # real signature unknown; restored from __doc__ """ S.isnumeric() -> bool Return True if there are only numeric characters in S, False otherwise. """ return False def isprintable(self): # real signature unknown; restored from __doc__ """ S.isprintable() -> bool Return True if all characters in S are considered printable in repr() or S is empty, False otherwise. """ return False def isspace(self): # real signature unknown; restored from __doc__ """ 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): # real signature unknown; restored from __doc__ """ S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): # real signature unknown; restored from __doc__ """ 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): # real signature unknown; restored from __doc__ """ S.join(iterable) -> str 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): # real signature unknown; restored from __doc__ """ S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return "" def lower(self): # real signature unknown; restored from __doc__ """ S.lower() -> str Return a copy of the string S converted to lowercase. """ return "" def lstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.lstrip([chars]) -> str Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def maketrans(self, *args, **kwargs): # real signature unknown """ Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result. """ pass def partition(self, sep): # real signature unknown; restored from __doc__ """ 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): # real signature unknown; restored from __doc__ """ S.replace(old, new[, count]) -> str Return a copy of 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): # real signature unknown; restored from __doc__ """ 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): # real signature unknown; restored from __doc__ """ S.rindex(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. Raises ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.rjust(width[, fillchar]) -> str 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): # real signature unknown; restored from __doc__ """ 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=-1): # real signature unknown; restored from __doc__ """ S.rsplit(sep=None, maxsplit=-1) -> list of strings Return a list of the words in 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, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in 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=None): # real signature unknown; restored from __doc__ """ S.splitlines([keepends]) -> 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): # real signature unknown; restored from __doc__ """ 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): # real signature unknown; restored from __doc__ """ S.strip([chars]) -> str 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. """ return "" def swapcase(self): # real signature unknown; restored from __doc__ """ S.swapcase() -> str Return a copy of S with uppercase characters converted to lowercase and vice versa. """ return "" def title(self): # real signature unknown; restored from __doc__ """ S.title() -> str Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case. """ return "" def translate(self, table): # real signature unknown; restored from __doc__ """ S.translate(table) -> str Return a copy of the string S in which each character has been mapped through the given translation table. The table must implement lookup/indexing via __getitem__, for instance a dictionary or list, mapping Unicode ordinals to Unicode ordinals, strings, or None. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted. """ return "" def upper(self): # real signature unknown; restored from __doc__ """ S.upper() -> str Return a copy of S converted to uppercase. """ return "" def zfill(self, width): # real signature unknown; restored from __doc__ """ S.zfill(width) -> str 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 __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ pass def __contains__(self, *args, **kwargs): # real signature unknown """ Return key in self. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __format__(self, format_spec): # real signature unknown; restored from __doc__ """ S.__format__(format_spec) -> str Return a formatted version of S as described by format_spec. """ return "" def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getitem__(self, *args, **kwargs): # real signature unknown """ Return self[key]. """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__ """ str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. # (copied from class doc) """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mod__(self, *args, **kwargs): # real signature unknown """ Return self%value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value.n """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __rmod__(self, *args, **kwargs): # real signature unknown """ Return value%self. """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __str__(self, *args, **kwargs): # real signature unknown """ Return str(self). """ pass
列表
列表用方括號表示(其餘語言稱爲數組)。
建立列表:
name_list = ['張三', '李四', 'web'] age_list = [25, 40, 20] lst = ['什麼鬼', 88, ['張三', '李四', 'web'], age_list] # 一個不明因此的列表
列表的元素,能夠是數字、字符串、列表、變量,還能夠是其餘任意類型的數據。
列表是序列類型,有索引,能夠按索引取值。
>>> name_list = ['張三', '李四', 'web'] >>> age_list = [25, 40, 20] >>> lst = ['什麼鬼', 88, ['張三', '李四', 'web'], age_list] # 查 用索引,-1表示最後一個 >>> name_list[0] '張三' >>> name_list[-1] 'web' >>> lst[2][0] '張三' # 增長 >>> name_list.append('王五') >>> name_list ['張三', '李四', 'web', '王五'] >>> name_list.insert(1, '插一個') >>> name_list ['張三', '插一個', '李四', 'web', '王五'] # 刪除 remove直接刪除,不可恢復 # pop能夠把刪除的值賦值給一個變量,pop默認刪除最後一個,也能夠指定索引 >>> name_list.remove('插一個') >>> name_list ['張三', '李四', 'web', '王五'] >>> w = name_list.pop(3) >>> w '王五' >>> name_list ['張三', '李四', 'web'] >>> wb = name_list.pop() >>> name_list ['張三', '李四'] # 改 >>> name_list[1] = 'web回來了' >>> name_list ['張三', 'web回來了']
>>> age_list [25, 40, 20, 15, 18] >>> age_list[:2] [25, 40] >>> age_list[:3:2] [25, 20] >>> age_list[1:3] [40, 20] >>> age_list[1:] [40, 20, 15, 18] >>> age_list[0:-1] [25, 40, 20, 15] >>> age_list[0:] [25, 40, 20, 15, 18] >>> age_list[::-1] # 列表逆序 [18, 15, 20, 40, 25] >>> age_list[-1::-1] [18, 15, 20, 40, 25]
""" 使用切片會產生一個新列表,須要用一個變量來保存 """ number_list = list(range(1, 101)) # 前兩個參數 slice1 = number_list[0:10] # 1-10 print(slice1) slice2 = number_list[10:20] # 10-20 print(slice2) # 第三個參數,無關緊要 # 正整數:步長 # 步長:按n個一組把列表分組,取每組第一個元素組成新的列表 slice3 = number_list[::2] print(slice3) slice4 = number_list[1::2] print(slice4) # 負整數:逆序+步長 slice5 = number_list[::-3] print(slice5)
切片:可接收三個參數,以冒號分隔。前兩個參數爲索引,最後一個索引可用-1代替。第三個參數可選,切片的步伐,即每幾個元素切一次。
指定索引時,不取到右索引對應值。兩個索引不指定時,默認最小和最大。
切片不會改變原列表,會從新申請內存空間,須要用一個變量去接收,頻繁使用切片會下降性能。
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) -> None -- append object to end """ pass def clear(self): # real signature unknown; restored from __doc__ """ L.clear() -> None -- remove all items from L """ pass def copy(self): # real signature unknown; restored from __doc__ """ L.copy() -> list -- a shallow copy of L """ return [] 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) -> None -- 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) -> None -- 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, key=None, reverse=False): # real signature unknown; restored from __doc__ """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """ pass def __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ pass def __contains__(self, *args, **kwargs): # real signature unknown """ Return key in self. """ pass def __delitem__(self, *args, **kwargs): # real signature unknown """ Delete self[key]. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __iadd__(self, *args, **kwargs): # real signature unknown """ Implement self+=value. """ pass def __imul__(self, *args, **kwargs): # real signature unknown """ Implement self*=value. """ 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, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value.n """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __reversed__(self): # real signature unknown; restored from __doc__ """ L.__reversed__() -- return a reverse iterator over the list """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __setitem__(self, *args, **kwargs): # real signature unknown """ Set self[key] to value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ L.__sizeof__() -- size of L in memory, in bytes """ pass __hash__ = None
>>> age_list = [25, 40, 20, 20, 20] # 統計某元素數量 >>> age_list.count(20) 3 # 反轉 >>> age_list.reverse() >>> age_list [20, 20, 20, 40, 25] # 排序 >>> age_list.sort() >>> age_list [20, 20, 20, 25, 40] # 清空列表 >>> age_list.clear() >>> age_list [] # 列表合併爲字符串 ''.join(),列表全部元素都爲字符串時,可將列表元素以指定字符合併爲一個字符串 >>> name_list ['張三', '老王'] >>> '-'.join(name_list) '張三-老王' >>> '******'.join(name_list) '張三******老王'
列表存儲的並非咱們看到的數據,而是這些數據的內存地址。
字典
字典是以鍵值對存儲的數據,用花括號表示,鍵和值以冒號分割,一個字典中能夠存在多個鍵值對,鍵值對之間以逗號分隔。字典是無序的。
字典的建立:
info = {'name': 'web', 'age': 25} 或者 info = dict(name='web', age=25)
# 查全部鍵 >>> info.keys() dict_keys(['name', 'age']) # 查全部值 >>> info.values() dict_values(['web', 25]) # 增長\修改 >>> info['sex'] = '男' # 若是已存在,則修改 >>> info {'name': 'web', 'age': 25, 'sex': '男'} >>> info.setdefault('age', 26) # 增長,已存在時不作修改 25 >>> info {'name': 'web', 'age': 25, 'sex': '男'} >>> info.setdefault('height', 176) 176 >>> info {'name': 'web', 'age': 25, 'sex': '男', 'height': 176} # 查 使用get方法時,若是不存在則返回None,不會報錯 >>> info['name'] 'web' >>> info.get('name') 'web' >>> info.get('xxx') # 刪除 >>> del info['sex'] >>> info {'name': 'web', 'age': 25, 'height': 176} >>> height = info.pop('height') >>> height 176 >>> info {'name': 'web', 'age': 25}
>>> info {'name': 'web', 'age': 25} >>> height = {'height': 176} >>> info.update(height) >>> info {'name': 'web', 'age': 25, 'height': 176} >>> age = {'age': 22} >>> info.update(age) >>> info {'name': 'web', 'age': 22, 'height': 176}
>>> from collections import OrderedDict >>> d1 = OrderedDict({'name': 'web', 'age': 25}) >>> d1 OrderedDict([('name', 'web'), ('age', 25)])
元組
元組的特性:
1. 可存放多個值
2. 不可變
3. 有序,可迭代,索引從0開始順序訪問
元組的建立:用圓括號表示
>>> ages = () >>> type(ages) <class 'tuple'> >>> names = tuple() >>> type(names) <class 'tuple'>
# 索引 >>> ages = (11, 22, 33, 44, 55) >>> ages[0] >>> ages[3] >>> ages[-1] # 切片:同list # 長度 >>> len(ages) # 包含 >>> 11 in ages True >>> 66 in ages False >>> 11 not in ages False
元組不可變,可是其某個元素若是是可變的,好比元組中包含的列表,並不影響列表的特性。
集合
集合與列表相似,可是集合內的元素是不容許重複的。用花括號表示。通常用於去重。工廠函數爲set()
>>> age = [12, 23, 25, 12, 30] >>> set_age = set(age) >>> set_age {25, 12, 30, 23} >>> age = list(set_age) >>> age [25, 12, 30, 23]
可變數據類型&不可變數據類型
每一個數據在內存中都有本身的內存地址,對於可變數據類型,修改後內存地址不變,對於不可變數據類型,修改意味着銷燬原內存,從新申請一個新的內存來保存數據。 查看內存地址用內置函數id()。
>>> age = [123, 456] >>> id(age)。 2437338179144 >>> age.append(121) >>> id(age) 2437338179144
可變數據類型:列表、字典、集合。
不可變數據類型:數字、字符串、元組