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'

  

  (1)声明变量  

#!/usr/bin/env python3
#-*- coding:utf-8-*-

name = "hello"

  上述代码声明了一个变量,变量名为:name, 变量name的值为"hello"。

  变量的作用:昵称,其代指内存里某个地址中保存的内容。

  (2)变量赋值

  在Python中,等号 = 是赋值语句,可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可以是不同类型的变量。

a = 123 # a 是整数
a = 'abc' # a 是字符串

  这种变量本身类型不固定的语言称之为动态语言,与之对应的就是静态语言。静态语言在定义变量时必须指定变量类型,如果赋值的时候类型不匹配,就会报错。例如Java是静态语言,赋值语句如下(//表示注释):

int a = 123;  // a 是整数类型变量
a = "abc"; // 错误:不能把字符串赋值给整型变量

  和静态语言相比,动态语言更灵活,就是这个原因。特别注意的是:不要将赋值语句的等号等同于数学的等号!

a = 1
a = a + 1
print(a)

  上述代码 a 的结果为 2,因为在程序中,赋值语句先计算右侧的表达式 a + 1,得到结果在赋值给a。最后 a = 2。

  理解变量在计算机内存中的表示非常重要~!

>>> name1 = 'hello'
>>> name2 = 'world'
>>> name3 = name2
>>> id(name1)
2463739724384
>>> id(name2)
2463739724496
>>> id(name3)
2463739724496
# 通过id这个内置函数,我们可以看到变量的内存地址
"""
 name2 和 name3 都是'world',看到他们的内存地址都是一样的,
说明在name3中并没有在内存中创建新内容而是将name3指向了已存在的'world',
name2和name3共同指向一个内存地址
"""

 

  

>>> name1 = 'hello'
>>> name2 = 'world'
>>> name3 = name2
>>> name2 = 'OK'
# name2 更换内容后,name3会怎样呢?

  

 二. 常量

  所谓常量就是不能变的变量,比如常用的数学常数π就是一个常量。在Python中,通常用全部大写的变量名表示常量:

BI = 3.14

  但事实上 BI 仍然是个变量,Python根本无法保证 BI 不会被改变,所以,用全部大写的变量名表示常量只是一个习惯上的用法,如果你一定要改,没人能拦得住你。

 

三. 数据类型

  不同的数据,需要定义不同的数据类型。在Python中,能够直接处理的数据类型如下:

(1)整数(int)

  Python可以处理任意大小的整数,当然也包括负整数。

(2)浮点数(float)

  浮点数也就是小数,之所以成为浮点数,是因为按照科学计数法表示时,一个浮点数的小数点位置是可以变的,比如1.23x10九次方(输入法写不出来呀)和12.3x10八次方是完全相等。

注意:整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的,而浮点数运算咋可能会有四舍五入的误差。

(3)字符串(string)

  字符串是以单引号 ' 或 双引号  " 括起来的内容,比如 'abc', "dfg"等等。请注意,单引号或双引号本身只是一种表示方式,不是字符串的一部分,如果一个字符串本身也包含单引号或者双引号,我们需要通过转义字符\来标识。

>>> a = 'I\'m \"OK\"!'
>>> print(a)
I'm "OK"!

  转义字符 \ 可以转义很多字符,比如 \n 标识换行, \t 标识制表符, 字符 \ 本身也要转义,所以 \\ 就表示字符 \ 。

  字符串运算符:

  •  +            # 字符串连接
  •  *             # 重复输出字符串,string*2 输出为stringstring
  • string[ : ]  # 通过索引获取字符串中的字符
  • in             # 成员运算符-如果字符串中包含给定的字符返回True, 否则为False
  • not in       # 如果字符串中不包含给定的字符返回True, 否则为False 
  • r/R           # 和转义符相同效果, print( r"\n") 可以直接输出 \n 
  • %             # 格式字符串,格式化输出时使用
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
字符串

 

(4)布尔值

  布尔值和布尔代数的表示完全一致,一个布尔值只有True, False两种,要么是True ,要么是 False,在Python中可以直接用True,False表示布尔值(请注意大小写),也可以通过布尔运算计算出来:

>>> True
True
>>> False
False
>>> 3 > 1
True
>>> 2 > 5
False

  布尔值可以用 and , or 和 not 运算:

  • and  与运算,只有所有条件为True,and 运算结果才是True
  • or     或运算,只要有一个为True,or运算结果就是True
  • not   非运算,把True变成False, False变成 True

(5)空值 (None)

  空值是Python里一个特殊的值,用 None 表示。 None 不能理解为0,因为 0 是有意义的,而 None 是一个特殊的空值。

 

(6)列表(list)

  常用的一种数据类型,和其他语言所指的数组基本一样。列表是一组有序的数据集合,可以将各种数据有序的放在列表中,并且可以对其进行增删改查,以及遍历。

  • 创建列表,只要把逗号分隔的不同的数据项使用中括号括起来即可。
  • 有序
  • 元素可重复
  • 支持索引,切片,加,乘,检查成员
  • 列表的索引从 0 开始

 

常见的列表操作

  • list.append('item')    # 向列表后面追加一个元素,位置在最后
  • list.insert(3, 'item')   # 插入一个新元素item, 位置索引为3
  • list.index('item')       # 返回item元素的索引值,如果有多个相同的元素,返回匹配到的第一个,从索引位0开始逐一匹配
  • list.count('item')       # 统计item 元素的个数
  • list.extend('list2')      # 将list2(所有元素)合并到list 中
  • list.sort()                  # 将列表排序,Python3版本中列表中如果有混合字符串和数字是不允许排序的
  • list.reverse()             # 将列表反转(元素的顺序)
  • list.pop()                  # 删除最后一个元素
  • list.remove('item')     # 删除指定的元素,如果有多个同名元素,那会删除从左数找到的第一个
  • del list[3:8]              # 删除索引3至8的元素,不包含索引8;del 可以删除很多,例如变量,列表,字典等等。
  • list3 = list1 + list2    # 两个列表相加,不会去除重复元素,列表允许重复的元素存在
  • len(list)                    # 返回列表的长度,即列表中元素的个数
  • list * 2                     # 返回一个新的列表,原列表中的元素的两倍
  • max(list)/min(list)     # 返回列表中的最大值/最小值
  • list(seq)                    # 将元组转换为列表

清空列表的方法

  • list = [ ]     # 如果数据量很大,希望快速释放内容,采用此方法
  • del list[:]    # 速度最快
  • list.clear()

复制列表

  • list.copy(list2)         # 浅复制,只是真正复制了第一层列表,如果列表中还有第二层列表则并不会完全复制过来(二层列表复制过来的只是内存地址而已)
  • list.copy.copy(list2)  # 和copy 类似
  • list.deepcopy(list2)   # 深复制,全部复制,无论列表中有几层列表,从在复制后重新创建,而不像浅复制只复制第一层

切片(slice)

  从列表中取出指定多个元素的方法。

  • list[ 0 : 3 ]   # 取出第0到第3个元素,不包括第4个,列表元素以第0个开始
  • list[ : 3]       # 意义同上,0可以不写(默认是从0开始)
  • list[ 2 : 5 ]   # 取第3到第5个
  • list[ : -3 ]     # 取从0至倒数第3个元素
  • list[ -3 : ]     # 取最后3个元素
  • list[ 1 : 8 : 2 ]  # 从1到8每隔一个取一个,2表示步长,即每隔几个元素取一个
  • list[ : : 2 ]     # 从头到尾每隔一个取一个
  • list[ : ]          # 输出整个列表

(7) 元组(tuple)

  元组和列表非常类似,但是元组一旦创建就不能修改。元组支持切片,但不支持赋值。元组的不可变使得代码更加安全,如果有可能,尽量使用元组而非列表。

  • t = ()      # 创建空元组
  • t = ( 1,)  # 创建只包含一个元素的元组,即使只有一个元素也需要用逗号分隔,否则将默认给 t 赋值为 1
  • t[ 1 : 5 ]  # 通过切片获取元组中的元素
  • t3 = t1 + t2  # 虽然元组不允许修改,但是可以通过拼接或得新的元组
  • del t        # 删除一个元组
  • t * 2        # 获得一个2倍t元素的元组
  • i in t         # 元组成员判断
  • tuple(seq)  # 将列表转换为元组

 关于元组元素不可变的示例:

>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])
>>> t[0] = 1
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    t[0] = 1
TypeError: 'tuple' object does not support item assignment

  示例分析:这个元组定义的时候有3个元素,分别是'a', 'b',和一个列表。首先我们来看下定义的时候元组的3个元素:

当我们把列表的元素‘A’, 'B'修改为'X'和'Y'后,元组变成了:

表面上看,元组元素确实变了,但其实变的不是元组的元素,而是列表的元素。元组一开始指向的列表并没有改变成别的列表。所以说,元组所说的“不变”是说,元组的每个元素指向永远不变。即指向'a',就不能改成指向‘b’,指向一个列表,就不能改成指向其他对象,但指向的这个列表本身是可变的。

 

(8) 字典(dict)

  字典使用key-value的形式存储数据。

  • key : value 格式,key是唯一的,key可允许的数据类型一直只有字符串和整数(数字首位不可为0),每对key-value 用逗号分隔,字典的key必须是不可变对象!
  • key 数量 => value 数量,key允许没有value而单独存在
  • 字典默认是无序的,通过人工干预可以变成有序
  • 查询速度很快,字典是基于hash表的原理实现的,是根据关键字(key/value)而直接访问在内存存储位置的数据结构。把键值通过一个函数的计算,映射到表中一个位置来访问记录,加速查询。这个映射函数叫做散列函数,存放记录的数组称作散列表

关于不可变对象字符串的说明

>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
>>> a
'abc'
---------------------------------------------

>>> a = 'abc'
>>> b = a.replace('a', 'A')
>>> b
'Abc'
>>> a
'abc'

要始终牢记的是,a 是变量,而‘abc’ 才是字符串对象!我萌经常说,对象a的内容是'abc',但其实是指,a本身是个变量,它指向的对象内容才是'abc':

当我们调用a.replace('a', 'A')时,实际上调用方法replace是作用在字符串对象'abc' 上的,而这个方法虽然名字叫replace,但却没有改变字符串'abc'的内容。相反,replace方法创建了一个新字符串'Abc'并返回,如果我们用变量b指向该新字符串就容易理解了。

所以,对于不变对象来说,调用对象本身的任意方法,也不会改变该对象自身的内容,相反,这些方法会创建新的对象并返回,这样就保证了不可变对象本身永远是不可遍的。

字典的常用操作

  • d['key']                           # 查看key 的value
  • d['key'] = 'new_value'       # 将key的value重新赋值为 ‘new_value’ 
  • d.popitem()                      # 随机删除一条数据,dict为空时用此语法会报错
  • del d                               # 删除字典d
  • del d['key']                      # 删除字典中指定的key
  • d.items()                         # 将字典中的key,value转换成列表的形式显示。
  • d.has_key('name')            # 判断字典中是否有一个叫name的key,存在则返回True;Python3中取消了这个参数
  • d.get('key')                      # 查找key,如果存在则返回对应的value,否则返回None
  • d.clear()                           # 清空字典
  • d.update(dict2)                # dict2是一个新字典,用新字典dict2更新字典d,如果dict2字典中key与d中重复,那冲突的key的value将被dict2中的覆盖,不存在则创建
  • d.fromkeys(['a', 'b', 'c'], 'Test')  # 根据列表['a', 'b', 'c'] 来创建字典里的key,后面的Test 就是默认的value,如果不指定的话,value默认为None
  • d.setdefault('x', 'test')        # 找一个key为‘x’的记录,如果这个key 不存在就创建‘x’:‘test’,如果存在这个key,就直接返回这个key的value值。

字典的遍历

  • 直接遍历
  • 转换成字典在遍历
# 直接遍历, 效率高
>>> info
{'b': 'Test', 'd': 'Alex', 'c': 'Test', 'a': 'fromDict2', 'e': 'frinDict2'}
>>> for i in info:
    print(i,info[i])
b Test
d Alex
c Test
a fromDict2
e frinDict2


# 转换成列表遍历,如果数据量大的时候,效率低,因为存在一个字典到列表转换的过程。
>>> for key,val in info.items():
    print(key,val)
b Test
d Alex
c Test
a fromDict2
e frinDict2
字典遍历实例

 

字典和列表的优势比较:

  • 字典查询和插入的速度极快,不会随着key的增加而变慢
  • 字典需要占用大量的内容,内存浪费多
  • 列表查询和插入的时间随着元素的增加而增加
  • 列表占用空间小,浪费内存少
  • 字典是一种用空间来换取时间的方式

(9)集合(set)

  • 无序,不重复的元素集
  • 基本功能包括:测试元素存在和消除重复元素
  • 集合对象支持: 并集(t | s) , 交集(t & s),差集(t - s),对称差集(t ^ s , 在t或s中,但是不会同时在t和s中)等数学运算
  • s = set([1, 2, 3, 4]) / s = {1, 2, 3, 4}  # 创建一个数值集合

 

集合的基本操作

  • s.add('x')                 # 添加一项,若 x 元素已经存在则不进行操作
  • s.update([x, y, z])     # 在集合 s 中添加多项
  • s.remove('x')            # 从集合中删除‘x’ ,  如果不存在则引发KeyError
  • len(s)                      # 返回集合的长度
  • x in s                       #集合成员测试
  • s.discard(x)             # 如果在集合s中存在元素x则删除,若元素不存在也不会报错
  • s.pop()                    # 删除并且返回集合s中的一个不确定元素,如果为空则引发KeyError
  • s.clear()                   # 删除集合s中的所有元素
  • s.union(t) / s|t          # 返回集合s 和集合t的并集,t可以是集合,列表,元组,字典
  • s.intersection(t)  / s & t  # 返回交集
  • s.difference(t) / s-t         # 返回在结合s中而不再t中的元素
  • s.symmetric_difference(t) / s^t  # 返回s和t的对称差集,即只存在其中一个集合中出现的元素 
  • s.issubset(t) / s <= t                 # 判断s是否是t的子集,返回布尔值
  • s.issuperset(t) / s >= t               # 判断t是否是s的子集,返回布尔值

 

posted @ 2017-02-21 14:27  王永存ღ  阅读(1115)  评论(0编辑  收藏  举报