语言基础之:内置函数

Python内置函数

#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Author: Fan Carey
# Version 1.0
# Created time: 
# Description:内置函数

# abs(x) 返回数字的绝对值。
print(abs(-1))
print(abs(-1.2345))
print(abs(1+2j))
# 输出:
# 1
# 1.2345
# 2.23606797749979

# all() 用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。
print(all([0, 1, 2, -5]))
print(all([1, 2, -5]))
# 输出
# False
# True

# any()用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。
print(any([0, 1, 2, -5]))
print(any([]))
# 输出:
# True
# False

# ascii()  类似 repr() 函数, 返回一个表示对象的字符串, 但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 \x, \u 或 \U 编码的字符。
# 生成字符串类似 Python2 版本中 repr() 函数的返回值。
a = ascii(['a', 'b', 1, 2])
print(type(a), a, [a])
# 输出
# <class 'str'> ['a', 'b', 1, 2] ["['a', 'b', 1, 2]"]
# >>> ascii('abc')
# 输出"'abc'"

# bin() 返回一个整数 int 或者长整数 long int 的二进制表示。
print(bin(3))
# 输出
# 0b11

# bool() 函数用于将给定参数转换为布尔类型,如果没有参数,返回 False。
print(bool([0]))
print(bool([]))
print(bool(0))
print(bool(1))
print(issubclass(bool, int))  # bool 是 int 子类
# 输出
# True
# False
# False
# True
# True

# bytearray() 方法返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。
b1 = bytearray('abcd', encoding='utf-8')
print(b1, b1[1])
b1[1] = 50
print(b1, b1[1])
print(bytearray([1, 2, 3]))
print(bytearray('abc', encoding='utf-8'))
# 输出
# bytearray(b'abcd') 98
# bytearray(b'a2cd') 50
# bytearray(b'\x01\x02\x03')
# bytearray(b'abc')

# bytes(): bytes 函数返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。它是 bytearray 的不可变版本。
b2 = bytes([1, 2, 3])
print(b2)
# 输出
# b'\x01\x02\x03'

# callable() 函数用于检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败;但如果返回 False,调用对象 object 绝对不会成功。
print(callable('c1'))
# 输出:False
def c1(a, b):
    return  a + b
print(callable(c1))  # 函数返回 True
# 输出:True
class C1:
    def method(self):
        return 0
print(callable(C1))  # 类返回 True
# 输出:True
c = C1()
print(callable(c))  # 没有实现 __call__, 返回 False
# 输出:False
class C2:
    def __call__(self, *args, **kwargs):
        return 0
print(callable(C2))
# 输出:True
c = C2()
print(callable(c))  # 实现 __call__, 返回 True
# 输出:True

# chr(i) 用一个整数作参数,返回一个对应的字符。
# i -- 可以是 10 进制也可以是 16 进制的形式的数字,数字范围为 0 到 1,114,111 (16 进制为0x10FFFF)。
print(chr(97))
print(chr(0x61))
# 输出
# a
# a

# compile()将一个字符串编译为字节代码。
str1 = 'for i in range(3): print(i)'
c2 = compile(str1, '', 'exec')
exec(c2)
# 输出
# 0
# 1
# 2
str2 = '1+2*3'
c3 = compile(str2, '', 'eval')
print(eval(c3))
# 输出:7


# complex() 用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。
print(complex(1))
print(complex(1, 2))
print(complex('1'))
print(complex('1+2j'))
# 输出
# (1+0j)
# (1+2j)
# (1+0j)
# (1+2j)

# delattr() 用于删除属性。
class Coordinate:
    x = 1
    y = 2
point = Coordinate()

print('x = ', point.x)
print('y = ', point.y)
delattr(Coordinate, 'y')
print('--删除 y 属性后--')
print('x = ', point.x)
# print('y = ', point.y)
# 输出: 
# x =  1
# y =  2
# --删除 y 属性后--
# x =  1

# dict()用于创建一个字典。
print(dict())
# 输出:
{}

# dir()不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。
# 如果参数包含方法__dir__(),该方法将被调用。
# 如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
print(dir())
# 输出
# ['C1', 'C2', 'Coordinate', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b1', 'b2', 'c', 'c1', 'c2', 'c3', 'i', 'point', 'str1', 'str2']

# divmod() 函数接收两个数字类型(非复数)参数,返回一个包含商和余数的元组(a // b, a % b)。
print(divmod(1, 2))
print(divmod(6, 3))
# 输出
# (0, 1)
# (2, 0)

# enumerate() 用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
str3 = ['a', 'b', 'c']
print(list(enumerate(str3)))

# eval()用来执行一个字符串表达式,并返回表达式的值。
x = 2
print(eval('x * 3'))
# 输出:6

# exec() 执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码。
exec('for i in range(3): print("i:", i)')
# 输出:
# i: 0
# i: 1
# i: 2

# filter()用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
# 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
def is_odd(n):
    return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5,6])
newlist = list(tmplist)
print(newlist)
# 输出:[1, 3, 5]

# frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。
f1 = frozenset(range(3))
print(f1)
f2 = frozenset('abc')
print(f2)
# 输出
# frozenset({0, 1, 2})
# frozenset({'b', 'c', 'a'})
# 为什么需要冻结的集合(即不可变的集合)呢?因为在集合的关系中,有集合的中的元素是另一个集合的情况,
# 但是普通集合(set)本身是可变的,那么它的实例就不能放在另一个集合中(set中的元素必须是不可变类型)。
# 所以,frozenset提供了不可变的集合的功能,当集合不可变时,它就满足了作为集合中的元素的要求,就可以放在另一个集合中了。

# getattr()用于返回一个对象属性值。
'''
>>> class Coordinate:
...     x = 1
...
>>> point = Coordinate()
>>>
>>> print(getattr(point, 'x'))  # 获取属性 x 值
1
>>> print(getattr(point, 'y'))  # 属性 y 不存在,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Coordinate' object has no attribute 'y'
>>> print(getattr(point, 'y', 2))  # 属性 y 不存在,但设置了默认值
2
>>>
'''

# globals() 返回一个全局变量的字典,包括所有导入的变量。
print(globals())
# 输出
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000287739B0910>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/python视频课程/凡Python/Day4/内置参数.py', '__cached__': None, 'a': "['a', 'b', 1, 2]", 'b1': bytearray(b'a2cd'), 'b2': b'\x01\x02\x03', 'c1': <function c1 at 0x0000028775832B80>, 'C1': <class '__main__.C1'>, 'c': <__main__.C2 object at 0x000002877562E3A0>, 'C2': <class '__main__.C2'>, 'str1': 'for i in range(3): print(i)', 'c2': <code object <module> at 0x00000287758345B0, file "", line 1>, 'i': 2, 'str2': '1+2*3', 'c3': <code object <module> at 0x0000028775834660, file "", line 1>, 'Coordinate': <class '__main__.Coordinate'>, 'point': <__main__.Coordinate object at 0x00000287758218B0>, 'str3': ['a', 'b', 'c'], 'x': 2, 'is_odd': <function is_odd at 0x00000287756251F0>, 'tmplist': <filter object at 0x0000028775821BB0>, 'newlist': [1, 3, 5], 'f1': frozenset({0, 1, 2}), 'f2': frozenset({'c', 'a', 'b'})}

# hasattr()用于判断对象是否包含对应的属性。
class Coordinate:
    x = 1
point = Coordinate()
print(hasattr(point, 'x'))
print(hasattr(point, 'y'))
# 输出
# True
# False

# hash() 获取一个对象(字符串或者数值等)的哈希值。
print(hash('admin'))
# 输出:2606590291917355180
# hash() 函数可以应用于数字、字符串和对象,不能直接应用于 list、set、dictionary。
# 在 hash() 对对象使用时,所得的结果不仅和对象的内容有关,还和对象的 id(),也就是内存地址有关。
class Test:
    def __init__(self, i):
        self.i = i
for i in range(3):
    t = Test(1)
    print(hash(t), id(t))

# help()用于查看函数或模块用途的详细说明。
# >>> help('sys')
# Help on built-in module sys:

# hex()
print(hex(80))
# 输出:0x50

# id() 返回对象的唯一标识符,标识符是一个整数。CPython 中 id() 函数用于获取对象的内存地址。
i1 = 'abc'
print(id(i1))
# 输出:2099586967728

# input() 接受一个标准输入数据,返回为 string 类型。
# i2 = input('integer:')
# print(type(i2), i2)
# i3 = input('string:')
# print(type(i3), i3)
# 输出
# integer:12
# <class 'str'> 12
# string:abc
# <class 'str'> abc

# int(x, base) 用于将一个字符串或数字转换为整型。x -- 字符串或数字。base -- 进制数,默认十进制。
# 1、若 x 为纯数字,则不能有 base 参数,否则报错;其作用为对入参 x 取整
print(int())
print(int(1))
print(int(1.2))
print(int('12', 16)) # 如果是带参数base的话,12要以字符串的形式进行输入,12 为 16进制,转换为十进制为18
print(int('0xa', 16))
# 2、若 x 为 str,则 base 可略可有。base 存在时,视 x 为 base 类型数字,并默认将其转换为 10 进制数字。若 x 不符合 base 规则,则报错。
# print(int('9', 2))  # 报错,因为2进制无9
# 输出:
# 0
# 1
# 1
# 18
# 10

# isinstance()来判断一个对象是否是一个已知的类型,类似 type()
# 基本类型如:int,float,bool,complex,str(字符串),list,dict(字典),set,tuple。
i3 = 1
print(isinstance(i3, int))
print(isinstance(i3, str))
print(isinstance(i3, (int, str, list, tuple, dict)))
# 输出
# True
# False
# True
# isinstance() 与type()的区别:
class A:
    pass
class B(A):
    pass
print(isinstance(A(), A))  # returns True
print(type(A()) == A)  # returns True
print(isinstance(B(), A))  # returns True
print(type(B()) == A)  # returns False

# issubclass()用于判断参数 class 是否是类型参数 classinfo 的子类。
class A:
    pass
class B(A):
    pass
print(issubclass(B, A))
# 输出:True

# iter() 用来生成迭代器。
i4 = [1, 2, 3]
for i in iter(i4):
    print(i)
# 输出
# 1
# 2
# 3

# len()返回对象(字符、列表、元组等)长度或项目个数。
l1 = 'abc'
print(len(l1))
# 输出:3

# list()用于将元组或字符串转换为列表。
tuple1 = (1, 2, 3, 4)
print('list for tuple1:', list(tuple1))
# 输出:list for tuple1: [1, 2, 3, 4]

# locals()以字典类型返回当前位置的全部局部变量。
def locals1(arg):
    x = 1
    print(locals())
locals1(2)
# 输出:{'arg': 2, 'x': 1}

# map()根据提供的函数对指定序列做映射。
# 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的迭代器。
# from collections import Iterator
map1 = map(lambda x: x*2, iter([1, 2, 3]))
# >>> print(isinstance(map1,Iterator))
# True
for i in map1: # map1为迭代器
    print(i)
# 输出
# 2
# 4
# 6

# max() 返回给定参数的最大值,参数可以为序列。
print ("max(1, 2, 3) : ", max(1, 2, 3))
# 输出:max(1, 2, 3) :  3

# min() 返回给定参数的最小值,参数可以为序列。
print ("min(1, 2, 3) : ", min(1, 2, 3))
# 输出:min(1, 2, 3) :  1

# memoryview()返回给定参数的内存查看对象(memory view)。
# 所谓内存查看对象,是指对支持缓冲区协议的数据进行包装,在不需要复制对象基础上允许Python代码访问。
mem1 = memoryview(bytearray('abc', encoding='utf-8'))
print(mem1[1])
print(mem1[-1])
print(mem1[1:3])
print(mem1[1:3].tobytes())
# 输出:
# 98
# 99
# <memory at 0x000002B134516DC0>
# b'bc

# next()返回迭代器的下一个项目。要和生成迭代器的iter() 函数一起使用。
it = iter([1, 2, 3])
while True:
    try:
        x = next(it)
        print(x)
    except StopIteration:
        break
# 输出:
# 1
# 2
# 3
# 如果传入第二个参数, 获取最后一个元素之后, 下一次next返回该默认值, 而不会抛出 StopIteration:
it = iter([1, 2, 3])
while True:
    x = next(it, 'a')
    print(x)
    if x == 'a':  # 无限返回的值为a
        break

# oct() 将一个整数转换成8进制字符串。
print(oct(10))
# 输出:0o12

# open() 函数用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。
# 注意:使用 open() 函数一定要保证关闭文件对象,即调用 close() 函数。
# f = open('test.txt')
# f.read()
# f.close()

# ord() 是 chr() 函数(对于 8 位的 ASCII 字符串)的配对函数,它以一个字符串(Unicode 字符)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值。
print(ord('a'))
# 输出:97
print(ord('你'))
# 输出:20320

# pow() 返回 xy(x的y次方) 的值。
print('pow(2,8):', pow(2,8))
# 输出:pow(2,8): 256

# print() 用于打印输出。
# objects -- 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
# sep -- 用来间隔多个对象,默认值是一个空格。
# end -- 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
# file -- 要写入的文件对象。
# flush -- 输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。
print('www', 'carey', 'com', sep='.')
# 输出:www.carey.com
# 使用 flush 参数生成一个 Loading 的效果:
import time
print('loading', end='')
for i in range(3):
    time.sleep(1)
    print('.', end='', flush=True)

# property([fget[, fset[, fdel[, doc]]]]) 在新式类中返回属性值。
# fget -- 获取属性值的函数
# fset -- 设置属性值的函数
# fdel -- 删除属性值函数
# doc -- 属性描述信息
# 目前还不会使用,后期补充

# round()返回浮点数 x 的四舍五入值,准确的说保留值将保留到离上一位更近的一端(四舍六入)。
print('round(2.675):', round(2.675))  # round(2.675): 3
print('round(2.675):', round(2.675, 1))  # round(2.675): 2.7
print('round(2.675):', round(2.675, 2))  # round(2.675): 2.67
# 按我们的想法返回结果应该是 2.68,可结果却是 2.67,为什么?
# 这跟浮点数的精度有关。我们知道在机器中浮点数不一定能精确表达,因为换算成一串 1 和 0 后可能是无限位数的,机器已经做出了截断处理。
# 那么在机器中保存的2.675这个数字就比实际数字要小那么一点点。这一点点就导致了它离 2.67 要更近一点点,所以保留两位小数时就近似到了 2.67。
# 以上。除非对精确度没什么要求,否则尽量避开用round()函数。近似计算我们还有其他的选择:
#     使用math模块中的一些函数,比如math.ceiling(天花板除法)。
#     python自带整除,python2中是/,3中是//,还有div函数。
#     字符串格式化可以做截断使用,例如 "%.2f" % value(保留两位小数并变成字符串……如果还想用浮点数请披上float()的外衣)。
#     当然,对浮点数精度要求如果很高的话,请用decimal模块。

# reversed()返回一个反转的迭代器。
r1 = 'abc'
print(list(reversed(r1)))
# 输出:['c', 'b', 'a']
for i in reversed(r1):
    print(i)
# 输出:
# c
# b
# a

# repr() 将对象转化为供解释器读取的形式。
r2 = 'abc'
print(repr(r2))
# 输出:'abc'
r3 = {'name': 'carey', 'age': 25}
print(repr(r3))
# 输出:{'name': 'carey', 'age': 25}

# range() 返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。
# range(start, stop[, step])
# start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
# stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
# step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
print(list(range(3)))
# 利用 list 函数返回列表,输出:[0, 1, 2]

# set() 创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
x = set('abc')
y = set('cde')
print(x & y)
# 输出:{'c'}

# setattr() 对应函数 getattr(),用于设置属性值,该属性不一定是存在的。
class Coordinate(object):
    x = 1
point = Coordinate()
print(getattr(point, 'x'))
setattr(point, 'x', 2)
print(getattr(point, 'x'))
setattr(point, 'y', 2)
print(getattr(point, 'y'))
# 输出:
# 1
# 2
# 2

# slice(start, stop[, step]) 实现切片
# start -- 起始位置
# stop -- 结束位置
# step -- 间距对象,主要用在切片操作函数里的参数传递。
slice1 = slice(5)
arr = range(10)
print(arr[slice1])
# 输出:range(0, 5)

# sorted(iterable, key=None, reverse=False)   对所有可迭代的对象进行排序操作。
# iterable -- 可迭代对象。
# key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
# reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
print(sorted([1, 3, 2, 5, 4]))
# 利用key进行倒序排序
print(sorted([1, 3, 2, 5, 4], key=lambda x: x*-1))
print(sorted([1, 3, 2, 5, 4], reverse=True))

# staticmethod 返回函数的静态方法。
class S(object):
    @staticmethod
    def f():
        print('carey')
S.f()  # 静态方法无需实例化 输出:carey
s2 = S()
s2.f()  # 也可以实例化后调用,输出:carey
# staticmethod 参数要求是 Callable, 也就是说 Class 也是可以的:
class C1(object):
    @staticmethod
    class C2(object):
        def __init__(self, val=1):
            self.val = val
        def shout(self):
            print("Python世界第%d!" % self.val)
tmp = C1.C2(0)
print(type(tmp))    # 输出 : <class '__main__.C1.C2'>
tmp.shout()         # 输出 : Python世界第0!

# str() 将对象转化为适于人阅读的形式。
s3 = 'abc'
print(str(s3))

# sum() 进行求和计算。
print(sum([1, 2, 3]))  # 输出:6
print(sum([1, 2, 3], 1))  # 列表计算总和后再加 1
print(sum((1, 2, 3), 2))  # 元组计算总和后再加 2

# super(type[, object-or-type]) 用于调用父类(超类)的一个方法。
# super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
# MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
class A:
    def add(self, x):
        y = x + 1
        print(y)
class B(A):
    def add(self, x):
        super().add(x)
b = B()
b.add(2)  # 3

# tuple 函数将可迭代系列(如列表)转换为元组。
list1 = [1, 2, 3]
tuple2 = tuple(list1)
print(tuple2)
# 输出:(1, 2, 3)

# type() 如果只有第一个参数则返回对象的类型,三个参数返回新的类型对象。
# isinstance() 与 type() 区别:
# type() 不会认为子类是一种父类类型,不考虑继承关系。
# isinstance() 会认为子类是一种父类类型,考虑继承关系。
# 如果要判断两个类型是否相同推荐使用 isinstance()。
print(type(1))
# 输出:<class 'int'>

# vars() 返回对象object的属性和属性值的字典对象。
print(vars())
# 输出:
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000020109050910>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/python视频课程/凡Python/Day4/内置参数.py', '__cached__': None, 'a': "['a', 'b', 1, 2]", 'b1': bytearray(b'a2cd'), 'b2': b'\x01\x02\x03', 'c1': <function c1 at 0x00000201093D2B80>, 'C1': <class '__main__.C1'>, 'c': <__main__.C2 object at 0x0000020109128190>, 'C2': <class '__main__.C2'>, 'str1': 'for i in range(3): print(i)', 'c2': <code object <module> at 0x00000201093D5190, file "", line 1>, 'i': 'a', 'str2': '1+2*3', 'c3': <code object <module> at 0x00000201093D5240, file "", line 1>, 'Coordinate': <class '__main__.Coordinate'>, 'point': <__main__.Coordinate object at 0x00000201093C1EE0>, 'str3': ['a', 'b', 'c'], 'x': {'a', 'c', 'b'}, 'is_odd': <function is_odd at 0x00000201091C51F0>, 'tmplist': <filter object at 0x00000201093C1C10>, 'newlist': [1, 3, 5], 'f1': frozenset({0, 1, 2}), 'f2': frozenset({'a', 'c', 'b'}), 'Test': <class '__main__.Test'>, 't': <__main__.Test object at 0x0000020109158610>, 'i1': 'abc', 'i3': 1, 'A': <class '__main__.A'>, 'B': <class '__main__.B'>, 'i4': [1, 2, 3], 'l1': 'abc', 'tuple1': (1, 2, 3, 4), 'locals1': <function locals1 at 0x00000201093D33A0>, 'map1': <map object at 0x00000201093C1E80>, 'mem1': <memory at 0x0000020109376F40>, 'it': <list_iterator object at 0x00000201093C1FA0>, 'time': <module 'time' (built-in)>, 'r1': 'abc', 'r2': 'abc', 'r3': {'name': 'carey', 'age': 25}, 'y': {'e', 'c', 'd'}, 'slice1': slice(None, 5, None), 'arr': range(0, 10), 'S': <class '__main__.S'>, 's2': <__main__.S object at 0x00000201093DD670>, 'tmp': <__main__.C1.C2 object at 0x00000201093DD6D0>, 's3': 'abc', 'b': <__main__.B object at 0x00000201093DD790>, 'list1': [1, 2, 3], 'tuple2': (1, 2, 3)}
# 对于 x = 1,这样的一个赋值语句,我们在执行后,名称 x 引用到值 1。这就像字典一样,键引用值,当然,变量和所对应的值用的是个"不可见"的字典。我们可以使用 vars 函数来返回这个字典:
# >>> x = 1
# >>> scope = vars()
# >>> scope["x"]
# 1

# zip() 用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
# 我们可以使用 list() 转换来输出列表。
# 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = [6, 7, 8, 9]
zip1 = zip(l1, l2)
print(zip1)  # 输出:<zip object at 0x000002C0D92BFD80>
print(list(zip1))  # 输出:[(1, 4), (2, 5), (3, 6)]
print(list(zip(l1, l3)))  # 元素个数与最短的列表一致 输出:[(1, 6), (2, 7), (3, 8)]
z1, z2 = zip(*zip(l1, l2))  # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
print(list(z1))  # 输出:[1, 2, 3]
print(list(z2))  # 输出:[4, 5, 6]

# __import__() 用于动态加载类和函数 。
# a.py文件代码:
# import os
# print('在 a.py 文件中 %s' % id(os))
#
# test.py文件代码:
# import sys
# __import__('a')  # 导入 a.py 模块
# 执行test.py文件,输出结果为:在a.py文件中4394716136

posted @ 2020-11-05 05:25  f_carey  阅读(6)  评论(0编辑  收藏  举报  来源