Python示例,用于unpack元组或序列或可迭代,以便该元组可能长于N个元素,从而导致“ 太多的值无法unpack ”异常。
1.打开任意长度的元组
Python“ star expressions”可用于unpack任意长度的元组。
example1.py
>>> employee = ('Lokesh', 'email@example.com', '111-222-333', '444-555-666')
>>> name, email, *phone_numbers = employee
>>> name
'Lokesh'
>>> email
'email@example.com'
>>> phone_numbers
['111-222-333', '444-555-666']
example2.py
>>> *elements, end = [1,2,3,4,5,6,7,8]
>>> elements
[1,2,3,4,5,6,7]
>>> end
8
2.unpack元组并丢弃不想要的值
If there is a mismatch in the number of elements, you’ll get an error.
example3.py
>>> record = ('Lokesh', 37, 72.45, (1, 1, 1981))
>>> name, *_, (*_, year) = record #Only read name and year
>>> name
'Lokesh'
>>> year
1981
学习愉快!