- 乘号:数字*, 表示乘法
- 倍数:字符串,列表,元组均可使用*
a = "123"
print(a*3)
123123123
b = [1,2,3]
print(b*3)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
c = (1,2,3)
print(c*3)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
d={'a':1,'b':2,'c':3}
print(d*3)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'dict' and 'int'
- 打包:定义函数时,*parameters表示传入可变长度参数,并且将参数放到一个元组中
def tempfun(*args):
print(args)
tempfun(1,2,3)
输出:(1, 2, 3)
- 解包:调用函数时,函数中输入多个参数,调用时输入的是列表或者元组,调用时在列表或者元组前面加上*,可以将列表或者元组解包成为单个的参数传递给函数
def tempfun(a,b,c):
print(a,b,c)
tempfun(*[1,2,3])
#tempfun(*(1,2,3))
输出:1 2 3
b = [1,2,3]
print(*b)
输出:1 2 3
zip函数中*的用法:
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。
s = ['boy', 'girl', 'man']
print(s)
print(type(s))
print(*s)
a= zip(*s)
print(a)
print(type(a))
for i in a:
print(i)
print(type(i))
['boy', 'girl', 'man']
<class 'list'>
boy girl man
<zip object at 0x7f6c3d870fc0>
<class 'zip'>
('b', 'g', 'm')
<class 'tuple'>
('o', 'i', 'a')
<class 'tuple'>
('y', 'r', 'n')
<class 'tuple'>
Process finished with exit code 0
s = ['boy', 'girl', 'man']
print(s)
print(type(s))
print(*s)
a= zip(*s)
print(a)
print(type(a))
print(list(a))
print(type(a))
for i in a: #前面用print(list(a)),a已经迭代完,所以这里for循环没有输出任何内容
print(i)
print(type(i))
['boy', 'girl', 'man']
<class 'list'>
boy girl man
<zip object at 0x7f5d019d0fc0>
<class 'zip'>
[('b', 'g', 'm'), ('o', 'i', 'a'), ('y', 'r', 'n')]
<class 'zip'>
a = [1,2,3]
b = [4,5,6,7]
zipped = zip(a,b) # 打包为元组的列表
print(list(zipped))
输出:[(1, 4), (2, 5), (3, 6)]
a = [1,2,3]
b = [4,5,6,7]
zipped = zip(a,b) # 打包为元组的列表
# print(list(zipped))
print(*zipped)
输出:(1, 4) (2, 5) (3, 6)
a = [1,2,3]
b = [4,5,6,7]
zipped = zip(a,b) # 打包为元组的列表
# print(list(zipped)) # python3 中要将此行注释掉,否则
a = zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式,这里相当于打包-解包-再次打包,但是由于打包的时候丢失了一些数据,所以回和原始数据不一样。
print(list(a))
输出:[(1, 2, 3), (4, 5, 6)]