当前位置: 首页 > news >正文

循序渐进Python3(三) -- 2 -- 内置函数

上一篇我们介绍了21个最常用到的函数,简单列一下,帮助回忆巩固:

1.abs

2.dict

3.float

4.help

5.input

6.int

7.len

8.list

9.max

10.min

11.pow

12.print

13.range

14.repr

15.reversed

16.round

17.sorted

18.str

19.sum

20.tuple

21.type

按字母顺序排名,是否还能想起他们的功能?参数用法?

 下面再介绍第二类内置函数:

1.all # 参数iterable:可迭代对象;全为真返回True,否则返回False

def all(*args, **kwargs): # real signature unknown
"""
Return True if bool(x) is True for all values x in the iterable.

If the iterable is empty, return True.
"""
eg.
>>> all(['a', 'b', 'c', 'd'])
True
>>> all(['a', 'b', '', 'd'])   # 空字符串为false
False
>>> all(['a', 'b', '0', 'd'])
True
>>> all(['a', 'b', 0, 'd']) # 0 为 false,但字符串‘0’ 为true
False
>>> all([])
True
>>> all({})
True
>>> all(())
True
>>> all(['a', 'b', 'c', []]) # 单独的空列表空字典空元组空字符串都为true,但是和别的为true的元素放在一起,就false了
False
 
 

2.any # 参数iterable:可迭代对象;任意一个为真返回True,全部为假返回False。和all类似

eg.
>>> any(['a', {}, [], ''])
True
>>> any([(), {}, [], '']) # 不想相信自己的眼睛?唉,没办法,事实如此。
False
>>> any([])
False
>>> any({})
False
>>> any('')
False
>>> any(())
False
 
 

 3 ascii # 类似repr

eg.

>>> a = ' 1 1 1 1 xx\n 222'
>>> print(a)
 1 1 1 1 xx
 222
>>> print(ascii(a))
' 1 1 1 1 xx\n 222'
>>> print(repr(a))
' 1 1 1 1 xx\n 222'

 4.bytes #  将字符串转换成bytes类型

 
 
def __init__(self, value=b'', encoding=None, errors='strict'): # known special case of bytes.__init__
"""
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object

Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer
# (copied from class doc)
"""
eg.
>>> s = "中文"
>>> type(s)
<class 'str'>
>>> b = bytes(s,encoding='utf-8')
>>> b
b'\xe4\xb8\xad\xe6\x96\x87'
>>> type(b)
<class 'bytes'>
 
 

 ******************************** ******************************** ******************************** ********************************

    Python 3最重要的新特性之一是对字符串和二进制数据流做了明确的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。 Python 3不会以任意隐式的方式混用str和bytes,,你不能拼接字符串和字节流,也无法在字节流里搜索字符串(反之亦然),也不能将字符串传入参数为字节流 的函数(反之亦然)。下面让我们深入分析一下二者的区别和联系。

    bytes是一种比特流,它的存在形式是01010001110这种。我们无论是在写代码,还是阅读文章的过程中,肯定不会有人直接阅读这种比特流,它必 须有一个编码方式,使得它变成有意义的比特流,而不是一堆的01组合。因为编码方式的不同,对这个比特流的解读也会不同,对实际使用造成了很大的困 扰。

    从刚才的例子可以看出,s是个字符串类型。内置函数bytes()可以将字符串转换成bytes类型,b实际上是一串01的组合,但为了 在ide环境中让我们相对直观的观察,它被表现成了
b'\xe4\xb8\xad\xe6\x96\x87'这种形式,开头的b表示这是一个bytes类 型。\xe4是十六进制的表示方式,它占用1个字节的长度,因此”中文“被编码成utf-8后,我们可以数得出一共用了6个字节,每个汉字占用3个,这印 证了上面的论述。在使用内置函数bytes()的时候,必须明确encoding的参数,不可省略。

    我们都知道,字符串类(str)里有一个encode()方法,它是从字符串向比特流的编码过程。而bytes类型恰好有个decode()方 法,它是从比特流向字符串解码的过程。除此之外,我们查看Python源码会发现bytes和str拥有几乎一模一样的方法列表,最大的区别就是 encode和decode。

  从实质上来说,字符串在磁盘上的保存形式也是01的组合,也需要编码解码。
  如果,上面的阐述还不能让你搞清楚两者的区别,那么记住下面两几句话:
  1.在将字符串存入磁盘和从磁盘读取字符串的过程中,Python自动地帮你完成了编码和解码的工作,你不需要关心它的过程。
  2.使用bytes类型,实质上是告诉Python,不需要它帮你自动地完成编码和解码的工作,而是用户自己手动进行,并指定编码格式。
  3.Python已经严格区分了bytes和str两种数据类型,你不能在需要bytes类型参数的时候使用str参数,反之亦然。这点在读写磁盘文件时容易碰到。
 
 

  在bytes和str的互相转换过程中,实际就是编码解码的过程,必须显式地指定编码格式。

 
 

 ******************************** ******************************** ******************************** ********************************

5.bytearray([source [, encoding [, errors]]]) # 返回一个byte数组。Bytearray类型是一个可变的序列,并且序列中的元素的取值范围为 [0 ,255]。
def __init__(self, source=None, encoding=None, errors='strict'): # known special case of bytearray.__init__
"""
bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
bytearray() -> empty bytes array

Construct a mutable bytearray object from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- a bytes or a buffer object
- any object implementing the buffer API.
- an integer
# (copied from class doc)
"""
参数source:
如果source为整数,则返回一个长度为source的初始化数组;
如果source为字符串,则按照指定的encoding将字符串转换为字节序列;
如果source为可迭代类型,则元素必须为[0 ,255]中的整数;
#如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray.
eg.
>>> a = bytearray(3)
>>> a
bytearray(b'\x00\x00\x00')
>>> bytearray(b'\x00\x00\x00')
bytearray(b'\x00\x00\x00')
>>> a[0]
0
>>> a[1]
0
>>> a[2]
0
 
 
>>> b = bytearray("abc",encoding='utf-8')
>>> print(b)
bytearray(b'abc')
>>> b
bytearray(b'abc')
>>> b[0]
97
>>> b[1]
98
>>> b[2]
99
>>> c = bytearray([1, 2, 3])
>>> c
bytearray(b'\x01\x02\x03')
>>> bytearray(b'\x01\x02\x03')
bytearray(b'\x01\x02\x03')
>>> c[0]
1
>>> c[1]
2
>>> c[2]
3

 6.callable # 判断对象是否可以被调用,能被调用的对象就是一个callables对象,比如函数和带有__call__()的实例。

def callable(i_e_, some_kind_of_function): # real signature unknown; restored from __doc__
"""
Return whether the object is callable (i.e., some kind of function).

Note that classes are callable, as are instances of classes with a
__call__() method.
"""
eg.
>>> callable(max)
True
>>> callable([1, 2, 3])
False
>>> callable('str')
False
>>> callable(str)
 
 

 7.chr # 查看十进制数对应的ASCII字符

def chr(*args, **kwargs): # real signature unknown
""" Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. """

8.ord # 查看某个ASCII对应的十进制数。
def ord(*args, **kwargs): # real signature unknown
""" Return the Unicode code point for a one-character string. """

eg.
>>> chr(0)
'\x00'
>>> ord('\x00')
0

 9.complex(self, real, imag=None) # 创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。

    参数real: int, long, float或字符串;

    参数imag: int, long, float。

eg.
>>> complex(1, 2)
(1+2j)
>>> complex(1)
(1+0j)
>>> complex("1")
(1+0j)
>>> complex("1+2j")
(1+2j)
 
 

 10.compile(source, filename, mode[, flags[, dont_inherit]])  # 将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。

def compile(*args, **kwargs): # real signature unknown
"""
Compile source into a code object that can be executed by exec() or eval().

The source code may represent a Python module, statement or expression.
The filename will be used for run-time error messages.
The mode must be 'exec' to compile a module, 'single' to compile a
single (interactive) statement, or 'eval' to compile an expression.
The flags argument, if present, controls which future statements influence
the compilation of the code.
The dont_inherit argument, if true, stops the compilation inheriting
the effects of any future statements in effect in the code calling
compile; if absent or false these statements do influence the compilation,
in addition to any features explicitly specified.
"""

参数source:字符串或者AST(Abstract Syntax Trees)对象。

参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。

参数model:指定编译代码的种类。可以指定为 ‘exec’,’eval’,’single’。

参数flag和dont_inherit:这两个参数暂不介绍,可选参数。

 eg.
>>> code = "for i in range(0, 10): print(i)"
>>> cmpcode = compile(code, '', 'exec')
>>> exec(cmpcode)
0
1
2
3
4
5
6
7
8
9
>>> s  = "print('helloworld')"
>>> r = compile(s, "<string>", "exec")
>>> r
<code object <module> at 0x00641AC0, file "<string>", line 1>
>>> exec(r)
helloworld
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17

 # exec 和 eval  这两个函数后面会介绍

11.dir # 不带参数时返回当前范围内的变量,方法和定义的类型列表,带参数时返回参数的属性,方法列表。

def dir(p_object=None): # real signature unknown; restored from __doc__
"""
dir([object]) -> list of strings

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
"""


eg.
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__',
 'a', 'b', 'c', 'cmpcode', 'code', 'i', 'r', 's', 'str', 'website', 'website_byt
es_gb2312', 'website_bytes_utf8', 'website_string', 'website_string_gb2312']
>>> dir(a)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge
__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '
__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '_
_sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_cod
e', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co
_kwonlyargcount', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksiz
e', 'co_varnames']

 12.divmod # 分别取商和余数

def divmod(x, y): # known case of builtins.divmod
""" Return the tuple (x//y, x%y). Invariant: div*y + mod == x. """
return (0, 0)


eg.
>>> divmod(20,6)
(3, 2)
>>> a,b = divmod(200,6)
>>> print(a,b)
33 2

 13.enumerate # 把可迭代对象转换为枚举对象。iterable是可迭代参数,比如像列表、数组、字典等对象;start是枚举的起始值,默认是从0开始。

                        这个函数实现原理是这样,从迭代对象的方法__next__()取得一项值,然后就对参数start开始计数,每取一项增加1,生成一个元组返回。

>>> help(enumerate)
Help on class enumerate in module builtins:

class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |
 |  Return an enumerate object.  iterable must be another object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument.
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

eg.

>>> l = ['a', 'b', 'c']
>>> print(list(enumerate(l)))
[(0, 'a'), (1, 'b'), (2, 'c')]
>>>
... t = ('快乐', '高兴', '开心')
>>> print(list(enumerate(t)))
[(0, '快乐'), (1, '高兴'), (2, '开心')]
>>>
... d = {'深圳':1, '广州':2, '珠海':3}
>>> print(list(enumerate(d, 2)))
[(2, '广州'), (3, '深圳'), (4, '珠海')]
>>>
>>> s = '北京是一个大城市。'
>>> print(list(enumerate(s, 1)))
[(1, '北'), (2, '京'), (3, '是'), (4, '一'), (5, '个'), (6, '大'), (7, '城'), (8
, '市'), (9, '。')]

 14.eval # 将字符串str或者是compile()返回的代码当成有效的表达式来求值并返回计算结果.

>>> help(eval)
Help on built-in function eval in module builtins:

eval(source, globals=None, locals=None, /)
    Evaluate the given source in the context of globals and locals.

    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

eg.

>>> s = "1+2*3"
>>> type(s)
<class 'str'>
>>> eval(s)
7

 可参看compile函数。

15.exec # 执行字符串或complie方法编译过的字符串,没有返回值

>>> help(exec)
Help on built-in function exec in module builtins:

exec(source, globals=None, locals=None, /)
    Execute the given source in the context of globals and locals.

    The source may be a string representing one or more Python statements
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

eg.

>>> exec("print('hello, world')")
hello, world
>>> exec("a = 2")
>>> a
2
>>> exec("a = 2 + 3")
>>> a
5
>>> exec("2 + 3")  #没有返回值

 16.format # 格式化输出字符串,format(value, format_spec)实质上是调用了value的__format__(format_spec)方法。

>>> help(format)
Help on built-in function format in module builtins:

format(value, format_spec='', /)
    Return value.__format__(format_spec)

    format_spec defaults to the empty string

[[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位)

基本方法的使用:

'''
可以指定所需长度的字符串的对齐方式:
< (默认)左对齐
> 右对齐
^ 中间对齐
= (只用于数字)在小数点后进行补齐
'''
eg.
tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')
  
tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])
  
tpl = "i am {0}, age {1}, really {0}".format("seven", 18)
  
tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])
  
tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
  
tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
  
tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
  
tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)
  
tpl = "i am {:s}, age {:d}".format(*["seven", 18])
  
tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)
  
tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})
 
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
 
tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)

 

>>> print('1:\t|{0:>10},'.format('wangyu'))
1:      |    wangyu,

>>> print('2:\t|{0:4.2f}'.format(1.1415926))
2:      |1.14

>>> print('3:\t|',format(1.1415926,'<10.2f'))
3:      | 1.14

>>> print('4:\t|{0:<10},{1:<15}'.format('wangyu',1.1415926))
4:      |wangyu    ,1.1415926

>>> print('5:\t|User ID: {uid} Last seen: {last_login}'.format(uid='root',last_l
ogin = '5 Mar 2008 07:20'))
5:      |User ID: root Last seen: 5 Mar 2008 07:20

>>> data = {'first': 'Hello', 'last': 'World!'}
>>> print('6:\t|{first} {last}'.format(**data))  # 这个是不是挺有意思?
6:      |Hello World!

>>> print('%(first)s %(last)s' % data)   # 百分号方式
Hello World!

 

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d};'.forma
t(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678;

 

>>> print('I\'m {},{}'.format('Hongten','Welcome to my space!'))  #使用'{}'占位符  
I'm Hongten,Welcome to my space!

 

#可以改变占位符的位置
>>> print('{1},I\'m {0},my E-mail is {2}'.format('Hongten','Hello','hongtenzone@
foxmail.com'))
Hello,I'm Hongten,my E-mail is hongtenzone@foxmail.com

 

#混合使用'{0}','{name}'形式 
>>> print('{0},I\'m {1},{message}'.format('Hello','Hongten',message = 'This is a
 test message!'))
Hello,I'm Hongten,This is a test message!

 '''

格式化指示符可以包含一个展示类型来控制格式。 例如,浮点数可以被格式化为一般格式或用幂来表示。

'b' - 二进制。将数字以2为基数进行输出。

'c' - 字符。在打印之前将整数转换成对应的Unicode字符串。

'd' - 十进制整数。将数字以10为基数进行输出。

'o' - 八进制。将数字以8为基数进行输出。

'x' - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。

'e' - 幂符号。用科学计数法打印数字。用'e'表示幂。

'g' - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。

'n' - 数字。当值为整数时和'd'相同,值为浮点数时和'g'相同。不同的是它会根据区域设置插入数字分隔符。

'%' - 百分数。将数值乘以100然后以fixed-point('f')格式打印,值后面会有一个百分号。

'''

>>> print('{0:e}'.format(3.75))
3.750000e+00

 打印乘法口诀:

for x in range(1, 10):
    for y in range(1, x+1):
        a = '{0:<2}* {1:<2}={2:<2}  '.format(y, x, x*y)
        print(a, end=' ')
    print('')

 

17.frozenset # 创建一个不可修改的集合。特点就是速度快,它是使用hash算法实现。参数iterable是表示可迭代的对象,比如列表、字典、元组等等。

>>> help(frozenset)
Help on class frozenset in module builtins:

class frozenset(object)
 |  frozenset() -> empty frozenset object
 |  frozenset(iterable) -> frozenset object
 |
 |  Build an immutable unordered collection of unique elements.

eg.

>>> l = [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]
>>> print(len(l), l)
11 [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]
>>> set = frozenset(l)
>>> print(len(set), set)
9 frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})

 

18.globals # 返回一个描述当前全局变量的字典

>>> help(globals)
Help on built-in function globals in module builtins:

globals()
    Return the dictionary containing the current scope's global variables.

    NOTE: Updates to this dictionary *will* affect name lookups in the current
    global scope and vice-versa.

 19.locals # 返回一个当前可用的局部变量的字典。

>>> help(locals)
Help on built-in function locals in module builtins:

locals()
    Return a dictionary containing the current scope's local variables.

    NOTE: Whether or not updates to this dictionary will affect name lookups in
    the local scope and vice-versa is *implementation dependent* and not
    covered by any backwards compatibility guarantees.

 20.hash # 返回对象object的哈希值。

>>> help(hash)
Help on built-in function hash in module builtins:

hash(obj, /)
    Return the hash value for the given object.

    Two objects that compare equal must also have the same hash value, but the
    reverse is not necessarily true.
eg.

>>> a = 'xxx'
>>> hash(a)
-1680135749
>>> hash('xxx')
-1680135749

 21.hex # 转换一个整数对象为十六进制的字符串表示,比如像0x的格式.

>>> help(hex)
Help on built-in function hex in module builtins:

hex(number, /)
    Return the hexadecimal representation of an integer.

    >>> hex(12648430)
    '0xc0ffee'

eg.

>>> print(hex(20))
0x14
>>> print(hex(128))
0x80
>>> print(hex(0x55))
0x55

22.oct # 转换一个整数对象为八进制的字符串

eg.

>>> oct(342391)
'0o1234567'

 23.bin # 转换一个整数对象为二进制的字符串

>>> bin(2796202)
'0b1010101010101010101010'

  24.id # 返回对象object的标识符,标识符类型为整数,在同一个时间里所有对象的标识符是唯一的,如果在不同生命周期的对象有可能有相同的标识符。比如创建对象A之后,再删除A,再创建对象B,对象A与对象B可能有相同的标识符。在CPython里的实现算法是直接返回对象所在内存地址。

>>> help(id)
Help on built-in function id in module builtins:

id(obj, /)
    Return the identity of an object.

    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)

 eg.

>>> a=[1,2,4,5,6]
>>> b=a
>>> print ('lista is : %s' % a,'\nlistb is : %s ' % b)
lista is : [1, 2, 4, 5, 6]
listb is : [1, 2, 4, 5, 6]
>>> a.append(9)
>>> print ('lista is : %s' % a,'\nlistb is : %s ' % b)
lista is : [1, 2, 4, 5, 6, 9]
listb is : [1, 2, 4, 5, 6, 9]
>>> b.append(100)
>>> print ('lista is : %s' % a,'\nlistb is : %s ' % b)
lista is : [1, 2, 4, 5, 6, 9, 100]
listb is : [1, 2, 4, 5, 6, 9, 100]
>>> print (id(a))
19623688
>>> print (id(b))
19623688

 25.zip # 接受任意多个(包括0个和1个)序列作为参数,返回一个tuple(对应位置的元素放在一个列表里)列表

>>> help(zip)
Help on class zip in module builtins:

class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 |
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.

 eg.

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> z = [7, 8, 9]
>>> xyz = zip(x, y, z)
>>> print(xyz)
<zip object at 0x012C2418>
>>> for i in xyz:print(i)
...
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)
>>> x = [1, 2, 3]
>>> y = [4, 5, 6, 7]
>>> xy = zip(x, y)
>>> print(xy)
<zip object at 0x012C2468>
>>> for i in xy:print(i)
...
(1, 4)
(2, 5)
(3, 6)
>>> x = [1, 2, 3]
>>> x = zip(x)
>>> print(x)
<zip object at 0x012C23F0>
>>> for i in x:print(i)
...
(1,)
(2,)
(3,)
>>> type(x)
<class 'zip'>
>>> print(zip())
<zip object at 0x012C24E0>
>>> for i in zip():print(i)
...

 26.bool # 测试一个对象是True还是False

>>> help(bool)
Help on class bool in module builtins:

class bool(int)
 |  bool(x) -> bool
 |
 |  Returns True when the argument x is true, False otherwise.
 |  The builtins True and False are the only two instances of the class bool.
 |  The class bool is a subclass of the class int, and cannot be subclassed.

 

转载于:https://www.cnblogs.com/wumingxiaoyao/p/5735377.html

相关文章:

  • SAP 创建物料主数据分类视图特性
  • ipa如何通过网络进行安装
  • 编译cdh的spark,使得支持spark-sql
  • Asp.net WebPages框架运行原理浅析(转)
  • 【Qt笔记】使用 QJsonDocument 处理 JSON
  • iOS - UILabel
  • html-table tbody加滚动条
  • vuex 学习笔记 01
  • Eclipse中web项目的默认发布路径改为外部Tomcat中webapp路径
  • 【NOIP】提高组2013 货车运输
  • AngularJS 用 Interceptors 来统一处理 HTTP 请求和响应
  • Ubuntu16.04 安装wine下的QQ
  • 1-2 ARM概况
  • 大数据美食——寻找地图上的美味
  • 使用python+hadoop-streaming编写hadoop处理程序
  • 分享一款快速APP功能测试工具
  • 【跃迁之路】【519天】程序员高效学习方法论探索系列(实验阶段276-2018.07.09)...
  • 07.Android之多媒体问题
  • C++类的相互关联
  • canvas 五子棋游戏
  • Java|序列化异常StreamCorruptedException的解决方法
  • leetcode388. Longest Absolute File Path
  • mac修复ab及siege安装
  • MySQL QA
  • MySQL数据库运维之数据恢复
  • select2 取值 遍历 设置默认值
  • XForms - 更强大的Form
  • 前端学习笔记之原型——一张图说明`prototype`和`__proto__`的区别
  • 用简单代码看卷积组块发展
  • 远离DoS攻击 Windows Server 2016发布DNS政策
  • 大数据全解:定义、价值及挑战
  • 如何用纯 CSS 创作一个菱形 loader 动画
  • ​2020 年大前端技术趋势解读
  • ${factoryList }后面有空格不影响
  • (07)Hive——窗口函数详解
  • (4.10~4.16)
  • (C#)Windows Shell 外壳编程系列9 - QueryInfo 扩展提示
  • (二开)Flink 修改源码拓展 SQL 语法
  • (剑指Offer)面试题34:丑数
  • (免费领源码)python+django+mysql线上兼职平台系统83320-计算机毕业设计项目选题推荐
  • (十五)Flask覆写wsgi_app函数实现自定义中间件
  • (收藏)Git和Repo扫盲——如何取得Android源代码
  • (已更新)关于Visual Studio 2019安装时VS installer无法下载文件,进度条为0,显示网络有问题的解决办法
  • (转)Java socket中关闭IO流后,发生什么事?(以关闭输出流为例) .
  • *setTimeout实现text输入在用户停顿时才调用事件!*
  • ./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’: ./incl
  • .MyFile@waifu.club.wis.mkp勒索病毒数据怎么处理|数据解密恢复
  • .net mvc 获取url中controller和action
  • .net连接MySQL的方法
  • .NET企业级应用架构设计系列之结尾篇
  • /etc/skel 目录作用
  • @angular/cli项目构建--http(2)
  • @Query中countQuery的介绍
  • [2021ICPC济南 L] Strange Series (Bell 数 多项式exp)
  • [android学习笔记]学习jni编程