假设有一个列表,其中有3个元素,如果用变量分别引用里面的这三个元素对象,可以如下操作:

>>> lst = ["learn python with laoqi", "you can find his books on line", "All of books are good"]
>>> x, y, z = lst
>>> x
'learn python with laoqi'
>>> y
'you can find his books on line'
>>> z
'All of books are good'

以上确定性的,如果不确定元素个数,怎么办?

此时,可以回忆在函数中如何捕获不确定数量的参数。

>>> x, *others = lst
>>> x
'learn python with laoqi'
>>> others
['you can find his books on line', 'All of books are good']

在变量前面增加一个“*”,就可以用该变量来收集迭代对象中其余元素。

有时候,我们也会使用“_”,意思是将迭代对象中某个元素忽略。

>>> lstint = list(range(10))
>>> lstint
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> _, x, *n = lstint
>>> x
1
>>> n
[2, 3, 4, 5, 6, 7, 8, 9]

上述两个小应用,在进行数据准备的时候回经常用到。比如,在整理有关用户联系方式的数据是,通常用户提供的电话号码不止一个。

>>> record = ("zhangsan", "zhangsan@hackdata.cn", "13813881499", "021-98765432")
>>> name, _, *phone = record
>>> name
'zhangsan'
>>> phone
['13813881499', '021-98765432']

小技巧,能有大惊奇。