python中*和**符号的用法系列(一):python中*用于序列解包
程序员文章站
2022-05-23 21:47:30
...
1、序列解包
使用*符号对序列解包适用于任意序列类型(序列类型包括string、list、tuple、set和dict)
str_test = "abc"
tuple_test = ("a","b","c")
list_test = ["a","b","c"]
print(*str_test)
print(*tuple_test )
print(*list_test )
结果1:a b c
结果2:a b c
结果3:a b c
2、利用 * 表达式获取单个变量中的多个元素
a, b, c = 1, 2, 3
获取剩余部分:
>>> a, b, *c = 0, 1, 2, 3
>>> a
0
>>> b
1
>>> c
[2, 3]
获取中间部分:
>>> a, *b, c = 0, 1, 2, 3
>>> a
0
>>> b
[1, 2]
>>> c
3
若左值数量比右值多,则带*号的默认为空:
>>> a, *b, c = 0, 1
>>> a
0
>>> b
[]
>>> c
1