数据类型

一、变量

  变量来源于数学,是计算机语言中能储存计算结果或能表示值抽象概念。变量可以通过变量名访问。

  python中定义一个变量非常简单

name = 'web'
age = 25

  那么调用name就会得到字符串‘web’,调用age就会得到数字25,可以通过print来查看。其中name、age为变量名,中间的 = 为赋值符号,'web'、25为变量值。

name, age = 'web', 25
一行定义多个变量

  变量的命名规则:

1、变量名只能是大小写字母、数字或下划线的任意组合,不能以数字开头。
2、不能使用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']
3、变量要表词达意,用英文单词。

  变量的定义方式:

驼峰体:
AgeOfWeb = 25

下划线:
age_of_web = 25

  其中驼峰体一般用于类的命名(面向对象),其他如变量、函数、实例化对象都使用下划线方式。

  常量:python中的变量都可以修改,约定俗成的方式,使用全大写字母表示常量。

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)
View Code

二、pthon基本数据类型

    数字    

  数字分为整型(int)和浮点型(float)

>>> age = 12
>>> height = 165.5
>>> type(age)        #type():查看数据类型的方法
<class 'int'>
>>> type(height)
<class 'float'>
>>> 10+313
>>> 10-37
>>> 10*330
>>> 10/33.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
字符串操作
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.'

3、 + 拼接(不推荐)
>>> "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)
View Code


切片:可接收三个参数,以冒号分隔。前两个参数为索引,最后一个索引可用-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

可变数据类型:列表、字典、集合。

不可变数据类型:数字、字符串、元组

原文地址:https://www.cnblogs.com/webc/p/8903108.html