###数据结构和算法-从任意长度的可迭代对象中分解元素
python3
从任意长的对象中分解元素:
def drop_first_last(grades):
first, *middle, last = grades
return middle
Python 3.7.1 (default, Dec 14 2018, 13:28:58)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> record = ('guo', 27, '13758214335', '13758214337')
>>> name,age,*number = record
>>> number
['13758214335', '13758214337']
>>> name
'guo'
>>> age
27
>>>
>>> *nums, last = [1, 2, 3, 4, 4, 5]
>>> nums
[1, 2, 3, 4, 4]
>>> last
5
>>> line = 'nobody:*:-2:-2:dhjhjjhjj User:/var/emprty:/usr/bin/false'
>>> uname, *fields, homedir, sh = line.split(':')
>>> uname
'nobody'
>>> fields
['*', '-2', '-2', 'dhjhjjhjj User']
>>> homedir
'/var/emprty'
>>> sh
'/usr/bin/false'
>>>
records = [
('foo', 1, 2),
('bar', 'hello'),
('foo', 3, 4)
]
def do_foo(x, y):
print('foo', x, y)
def do_bar(s):
print('bar', s)
for tag, *args in records:
if tag == 'foo':
do_foo(*args)
elif tag == 'bar':
do_bar(*args)
####执行结果
foo 1 2
bar hello
foo 3 4
大神用迭代
items = [1, 2, 3, 4, 5]
def sum(items):
head, *tail = items
return head + sum(tail) if tail else head
print (sum(items))
#执行结果
15