从下图中可以知道python3中有如下这些内置函数
图一
下面我们一一了解下每个函数的用法:
abs()
abs()
函数是取绝对值的函数,在C语言只中有也有一个abs()
函数但是在C语言中abs()
函数的参数要求是整数,在C语言中如果要对一个浮点数取绝对值则应该用fabs()
函数,但是在python中则不一样,abs()
函数是对参数没有要求的 ,不管是整数函数浮点数都可以,并且在使用abs()
函数是你传递的参数是什么类型的,返回的函数的类型也是相对应的类型
>>> abs(-1)
1
>>> abs(-2.0)
2.0
>>> type(abs(-2.4))
<class 'float'>
>>> type(abs(-2))
<class 'int'>
all() any()
all()
和 any()
功能类似都是判断一个可迭代对象是否为真
这两个函数的返回值都是boolean
值
首先我们应该了解在python3中哪些数据会被判断为False
a = 0 # 整数0,False
print(bool(a))
s = "" # 空字符串,False
print(bool(s))
lst = [] # 空列表,False
print(bool(lst))
dic = {} # 空字典,False
print(bool(dic))
a = None # None表示空,真空,False
print(bool(a))
除了以上数据,则都会被判断为True
all() any()的英文文档描述
all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
# 如果可迭代对象中的所有元素都是Ture则返回True,也可以理解为把可迭代对象中的所有元素做与运算
# 函数原型为
def all(iterable):
for element in iterable:
if not element:
return False
return True
例子
>>> all(['a',(2,4),1,True]) #list都为真
True
>>> all(['a',(),1,True]) #list元素中有空tuple
False
>>> all(['a',(2,4),0,True]) #有0
False
>>> all(['a',(2,4),3,False]) #有False
False
any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:
# 如果可迭代对象中存在元素是Ture则返回True,也可以理解为把可迭代对象中的所有元素做或运算
#函数原型为
def any(iterable):
for element in iterable:
if element:
return True
return False
例子
>>> any(['a',(2,4),3,True])
True
>>> any(['a',(2,4),3,False])
True
>>> any(['a',(),3,False])
True
>>> any(['',(),0,False])
False
>>> any(('a',(),3,False))
True
>>> any(('',(),0,False))
False
ascii(object)
返回一个可打印的对象字符串方式表示,如果是非ascii字符就会输出\x,\u或\U等字符来表示。与python2版本里的repr()是等效的函数。
>>> ascii(1)
'1'
>>> ascii('$')
"'$'"
>>> ascii(999999)
'999999'
>>> ascii('中国')
"'\\u4e2d\\u56fd'"
bin(), oct(), hex()
bin()
把十进制转化为二进制
>>> bin(7)
'0b111'
>>> bin(-7)
'-0b111'
>>> bin(1.1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
oct()
把十进制转化为8进制
>>> oct(10)
'0o12'
>>> oct(-10)
'-0o12'
>>> oct(-10.4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
hex
把十进制数转化为16进制
>>> hex(17)
'0x11'
>>> hex(-17)
'-0x11'
>>> hex(17.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
注意参数只能是整数
bool()
测试一个对象是True还是False.
>>> bool([])
False
>>> bool([''])
True
>>> bool(())
False
>>> bool(0)
False
>>> bool(4)
True
>>> bool(1.1)
True
>>> bool({})
False
>>> bool(['hello', 'world'])
True
bytes()
将一个字符串转换成字节类型
我们都知道在计算机的底层都是保存的二进制信息不管是数字还是文字都是转化为相对应的二进制格式保存在硬盘之中
我们都知道比如一个十进制的数字15
转化为二进制位1111
,直接把1111
保存在计算机中,但是我们的文字文本信息是怎么转化为这种二进制信息的呢?
这里就要涉及到计算机中的编码技术,我们最熟知的编码无非就是ASCII
编码了,但是在ASCII
编码中并没有中文字符的编码规范,然后为了在计算机中表示中文,相应的兼容中文的编码规范就出台了,比如有GB2312
, GBK
, UTF-8
等等。(最常用的还是UTF-8
)
UTF-8的具体规范
GBK规范
这里我们只需要了解,一个中文汉子用GBK
编码需要2字节,用UTF-8
需要三个字节
例子
>>> bytes('中国', encoding='utf-8')
b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> bytes('中国', encoding='UTF-8') # 编码格式不区分大写小写
b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> bytes('中国', encoding='gbk')
b'\xd6\xd0\xb9\xfa'
bytearray()
bytearray()
函数的官方文档描述是:
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)
"""
pass
- 当三个参数都不传时
>>> b = bytearray()
>>> b
bytearray(b'')
>>> len(b)
0
- 当source参数为字符串时,encoding参数也必须提供,函数将字符串使用str.encode方法转换成字节数组
>>> bytearray('中文')
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
bytearray('中文')
TypeError: string argument without an encoding
>>> bytearray('中文','utf-8')
bytearray(b'\xe4\xb8\xad\xe6\x96\x87')
- 当source参数为整数时,返回这个整数所指定长度的空字节数组
>>> bytearray(2)
bytearray(b'\x00\x00')
>>> bytearray(-2)
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
bytearray(-2)
ValueError: negative count
传递的整数参数需大于0,使用来做数组长度的
- 当source参数是一个可迭代对象,那么这个迭代对象的元素都必须符合0 <= x < 256,以便可以初始化到数组里
>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> bytearray([256,2,3]) #不在0-255范围内报错
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
bytearray([256,2,3])
ValueError: byte must be in range(0, 256)
callable()
callable()
函数用于检查一个对象是否是可调用的。如果返回True
,object
仍然可能调用失败;但如果返回False
,调用对象ojbect
绝对不会成功。
对于函数, 方法, lambda 函式, 类, 以及实现了 __call__
方法的类实例, 它都返回 True。
例子
>>>callable(0)
False
>>> callable("runoob")
False
>>> def add(a, b):
... return a + b
...
>>> callable(add) # 函数返回 True
True
>>> class A: # 类
... def method(self):
... return 0
...
>>> callable(A) # 类返回 True
True
>>> a = A()
>>> callable(a) # 没有实现 __call__, 返回 False
False
>>> class B:
... def __call__(self):
... return 0
...
>>> callable(B)
True
>>> b = B()
>>> callable(b) # 实现 __call__, 返回 True
True
chr() ord()
chr()
函数是把Unicode
字符转化为对应的十进制数字
ord()
函数则相反这是把数字转为对应的Unicode
字符,不一定是十进制其他进制也可以
例子
>>> ord('你')
20320
>>>ord('a')
97
>>> ord('b')
98
>>> ord('c')
99
>>> ord('ab')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
>>> chr(97)
'a'
>>> chr(65)
'A'
>>> chr(20320)
'你'
>>> chr(3874298)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(0x110000)
chr 的参数应该比0x110000小
compile() exec() eval()
compile(str, file, type)
我们知道我们写出来的源代码都是需要进行编译或者翻译成机器码才能被我们的计算机执行,compile
语句的目的是提供一次性的字节码编译,就不用在以后的每次调用中重新进行编译了。
还需要注意的是,这里的compile和正则表达式中使用的compile并不相同,尽管用途一样。
例子
>>> c = compile(str,'<string>','exec')
>>> c
<code object <module> at 0x100dbfed0, file "<string>", line 1>
>>> exec(c)
0
1
2
>>> str = 'print("hello")'
>>> c = compile(str,'<string>','eval')
>>> eval(c)
hello
>>> single_code = compile( 'print("pythoner.com")', '<string>', 'single' )
>>> exec(single_code)
pythoner.com
>>> eval(single_code)
pythoner.com
compile语句是从type类型(总共有三种类型包括'
eval
','exec
','single
': 着山中类型分别的用法是,single
便是我们编译的代码只有一行,eval
表示会把字符串编译成一个表达式,exec
表示会把字符串编译成一个和python一模一样的东西,比如就可以有for 循环 )中将字符串语句创建成代码对象。
eval()
eval()还可以单独直接执行表达式
例子
>>> eval('3*2')
6
>>> eval('print("hello world!")')
hello world!
exec()
exec()可以把符合python规范的字符串当成python语句进行执行,如果直接用这种方式执行每次都得编译一次
例子
>>> exec('for i in range(3): print(i)')
0
1
2
>>> exec('print(4)')
4
>>> exec('9*9')
eval执行表达式后是具有返回值的,但是exec是没有返回值的
complex()
函数为:complex([real[, imag]])
complex()函数是处理复数的函数具体有如下用法:
例子
- 当两个参数都不提供时,返回复数
0j
。(j
是python中的复数标志,和我们数学课上学过的i
是一样的)
>>> complex()
0j
- 当第一个参数为字符串时,调用时不能提供第二个参数。此时字符串参数,需是一个能表示复数的字符串,而且加号或者减号左右不能出现空格。
>>> complex('2.3+9j')
(2.3+9j)
>>> complex('3+3j', 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: complex() can't take second arg if first is a string
>>> complex('2 + 3j')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: complex() arg is a malformed string
- 当第一个参数为int或者float时,第二个参数可为空,表示虚部为0;如果提供第二个参数,第二个参数也需为int或者float。
>>> complex(2)
(2+0j)
>>> complex(3.1)
(3.1+0j)
>>> complex(3,4.2)
(3+4.2j)
dict()
dict() 函数用于创建一个字典。返回一个字典
>>>dict() # 创建空字典
{}
>>> dict(a='a', b='b', t='t') # 传入关键字
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函数方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)]) # 可迭代对象方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
dir()
函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法dir(),该方法将被调用。如果参数不包含dir(),该方法将最大限度地收集参数信息。
例子
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'i']
>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
divmod()
函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。
例子
>>>divmod(7, 2)
(3, 1)
>>> divmod(8, 2)
(4, 0)
>>> divmod(1+2j,1+0.5j) #复数也可以进行出发运算
((1+0j), 1.5j)
>>> div(12.3,7) # 只能进行整数的出发运算
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'div' is not defined
enumerate()
函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
例子
>>> enumerate([3,7,8])
<enumerate object at 0x10fc05948>
>>> list(enumerate([3,7,8]))
[(0, 3), (1, 7), (2, 8)]
>>> list(enumerate([3,7,8], start=4))
[(4, 3), (5, 7), (6, 8)]
使用for循遍历一个list
>>> i=0
>>> seq = ['pig', 'panda', 'duck']
>>> for ele in seq:
... print(i, ele)
... i+=1
...
0 pig
1 panda
2 duck
结合enumerate使用for循环遍历
>>> seq = ['pig', 'panda', 'duck']
>>> for n, ele in enumerate(seq):
... print(n, ele)
...
0 pig
1 panda
2 duck
id()
函数用于获取对象的内存地址。
在python中既可以进行面对对象的编程,也可以面对过程的编程,但是总的来说一切皆对象
,这句话不不容易理解的,需要我们对编程有深层次的学习后才能完全的体会到这句话的含义,但是我们不用着急学习的过程总是循序渐进的。
>>> id(seq)
4559234440
>>> id([])
4559234568
>>> a = 1
>>> id(a)
4555139008
isinstance()
判断一个一个对象是否是一个类的实例,或者判断一个对象是否是一个类的子类的实例
这了的概念是和类有关的,如果看不懂则先去学习一个python面对对象编程
例子
>>> a = 1
>>> id(a)
4555139008
>>> isinstance(a, int)
True
>>> s = 'string object'
>>> isinstance(s, str)
True
>>> isinstance(s, dict)
False
filter()
filter() 函数用于过滤序列(对一个可迭代对象进行筛选,去掉不需要的元素),过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
例子
需求去除序列[1,2,3,4,5,6]中的奇数
普通方法
>>> lis = [1,2,3,4,5,6]
>>> ret = []
>>> def get_even_number_list(lis):
... for i in lis:
... if i % 2 == 0:
... ret.append(i)
...
>>> get_even_number_list(lis)
>>> ret
[2, 4, 6]
使用filter
方法
>>> isinstance(s, dict)
False
>>> lis = [1,2,3,4,5,6]
>>> def is_even_number(x):
... if x%2 == 0:
... return True
... else:
... return False
...
>>> list(filter(is_even_number, lis))
[2, 4, 6]
>>> list(filter(lambda x:x%2==0, lis)) #如果使用lambda表达式会更加简单
[2, 4, 6]
从上面两个的做法中我们就可以比较两个方法,使用filter方法还是很方便的
map()
map()
函数的功能是接受两个参数,前一个是一个方法,后一个是一个可迭代对象,map()
是把每一个可迭代对象中的元素去除做一定操作然后更新这个元素
例子
>>> lis = [101, 102, 103, 104, 105, 106]
>>> map(lambda x:x-50, lis)
<map object at 0x1064be588>
>>> list(map(lambda x:x-50, lis))
[51, 52, 53, 54, 55, 56]
在python2.7以后
map
filter
函数的返回值是返回一个可迭代对象
globals() locals()
globals()
是获取有的全局变量
locals()
是获取有的局部变量
例子
>>> g = 1
>>> def f():
... a = 2
... print(globals())
... print(locals())
...
>>> f()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'g': 1, 'f': <function f at 0x1018ebe18>} #存在的全局变量
{'a': 2} #局部变量
hash()
hash()
哈希本来是密码学中的一种消息摘要算法,用途很广泛。如果像深入的了解什么是哈希函数,可以去百度上学习学习
例子
>>> s = 'hello'
>>> hash(s)
779082262045361556
>>> type(hash(s))
<class 'int'>
int()
int()
函数用于将一个字符串或数字转换为整型。
int()
函数有两个参数分别是int(x, base=10)
- x -- 字符串或数字。
- base -- 进制数,默认十进制。
例子
>>>int() # 不传入参数时,得到结果0
0
>>> int(3)
3
>>> int(3.6)
3
>>> int('12',16) # 如果是带参数base的话,12要以字符串的形式进行输入,12 为 16进制
18
>>> int('0xa',16)
10
>>> int('10',8)
8
input()
大家都知道python有2.X和3.X版本的但是现在很多都是使用python3了,这只只讨论3版本。
在python3.X中raw_input( )和input( )进行了整合,在3.X版本中去除了raw_input( ),仅保留了input( )函数,其接收任意任性输入,将所有输入默认为字符串处理,并返回字符串类型。
如果像了解下python2.X的input函数可以去菜鸟教程上学习下这里不做过多的讲解了
在python3中的input()
函数中所有的输入都就被当成是字符串
例子
>>> a = input('input:')
input:string
>>> type(a)
<class 'str'>
>>> i = int(input('input int number:')) # 这样可以直接输入一个整型
input int number:13
>>> type(i)
<class 'int'>
>>> i = float(input('输入一个浮点数:')) #输入一个浮点数
输入一个浮点数:1.4
>>> type(i)
<class 'float'>
len()
这是一个使用非常频繁的函数,并且是一个很强大的函数
返回对象(字符、列表、元组等)长度或项目个数。
例子
>>> string = 'testing'
>>> len(string)
7
>>> li = [1,2,3]
>>> len(li)
3
>>> dic = {'1':3,'3':5}
>>> len(dic)
2
>>> tu = (12,45,)
>>> len(tu)
2
这里提醒下python2中的len()
函数在计算中文字符串的长度的时候是以字符串占用的字节数来计算的,下面请看例子:
Python 2.7.15 (default, May 1 2018, 16:44:08)
[GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> bytes('你是')
'\xe4\xbd\xa0\xe6\x98\xaf'
>>> len('你是')
6
但是在python3中,len()
函数还是以字符个数来计算长度
list()
把一个元组转化为列表,或者一个可迭代的对象转化为列表
例子
>>> str="Hello World"
>>> list2=list(str)
>>> list2
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> aTuple = (123, 'Google', 'Runoob', 'Taobao')
>>> list1 = list(aTuple)
>>> print ("列表元素 : ", list1)
列表元素 : [123, 'Google', 'Runoob', 'Taobao']
max() min()
max()
min()
函数分别是区最大值和最小值
具体的可以看输入的例子学习下面的用法
>>> max(80, 100, 1000)
1000
>>> max((1,2,3,4))
4
>>> min((1,2,3,4))
1
>>> s = '12345'
>>> print(max(s))
5
>>> print(max((),default=1))
1
>>> print(max(())) #传入可迭代对象为空时,必须指定参数default,用来返回默认值
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence
>>> s = [
... {'name': 'sumcet', 'age': 18},
... {'name': 'bbu', 'age': 11}
... ]
>>> max(s, key=lambda x: x['age'])
{'name': 'sumcet', 'age': 18}
>>> prices = {'HPQ': 37.2, 'FB': 10.75, 'AAPL': 612.78, 'IBM': 205.55, 'ACME': 45.23}
>>> max(prices, key=lambda k: prices[k])
'AAPL'
min 和 max 的用法都是一样的只是得到的结果是一个是最大一个是最小
pwd()
计算一个次方
例子
>>> 2**4
16
>>> pow(2, 4)
16
reversed()
reversed()
方法是取一有序序列的反序,可以是 tuple, string, list 或 range。
例子
>>> l = [1,2,3,4]
>>> l.reverse() # str对象中的reverse方法页具有反转的功能
>>> l
[4, 3, 2, 1]
>>> reversed(l) # reversed() 的返回值是一个对象,如果可以我们可以把它转为list或者是tuple
<list_reverseiterator object at 0x10aa0a898>
>>> l
[4, 3, 2, 1]
>>> l
[4, 3, 2, 1]
>>> list(reversed(l))
[1, 2, 3, 4]
>>> tuple(reversed(l))
(1, 2, 3, 4)
>>> list(reversed('AbcdefG'))
['G', 'f', 'e', 'd', 'c', 'b', 'A']
round()
round()
函数是取浮点数也就是小数的保留位数
round 有两个参数,第一个是你要进行保留的小数,第二个是你像保留的位数,如果不传值默认为0,也就是默认保留到个位。
例子
>>> round(70.23456)
70
>>> round(56.659,1)
56.7
>>> round(80.264, 2)
80.26
>>> round(-100.000056, 3)
-100.0
set()
函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
例子
>>>x = set('runoob')
>>> y = set('google')
>>> x, y
(set(['b', 'r', 'u', 'o', 'n']), set(['e', 'o', 'g', 'l'])) # 重复的被删除
>>> x & y # 交集
set(['o'])
>>> x | y # 并集
set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
>>> x - y # 差集
set(['r', 'b', 'u', 'n'])
range()
range(start, stop[, step])
特别常用
range函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。
- 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
- 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5。
- 步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
例子
>>> range(10)
range(0, 10)
>>> range(2,10)
range(2, 10)
>>> range(1,4,2)
range(1, 4, 2)
>>> for i in range(1,4,2):
... print(i)
...
1
3
>>> for i in range(0,3,-1):
... print(i)
...
>>> for i in range(3,0,-1):
... print(i)
...
3
2
1
zip()
函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
我们可以使用 list() 转换来输出列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 *
号操作符,可以将元组解压为列表。
例子
压缩
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> v = [7,8,9]
>>> zip(a,b,v)
<zip object at 0x10aa0e848>
>>> list(zip(a,b,v)) # 把a,b,v压缩在一起
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> v = [7,8,9,10]
>>> list(zip(a,b,v)) # 如果数量不一样多则会丢掉多余的,这里就把10丢掉了
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
解压
>>> list(zip(a,b,v))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> ret = zip(a,b,c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
>>> ret = zip(a,b,v)
>>> list(zip(*ret))
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
网友评论