Python星号表达式

有时候可能想分解出某些值然后丢弃它们,可以使用诸如 _ 或者 ign(ignored)等常用来表示待丢弃值的变量名:
record = ('ACME', 50, 123.45, (12, 18, 2012))
name, *_, (*_, year) = record
print(name)
print(year)
# 结果为:
# ACME
# 2012
*表达式 在递归中的应用:
def sum(items):
    head, *tail = items
    return head + sum(tail) if tail else head
items = [1, 10, 7, 4, 5, 9]
print(sum(items))
# 结果为:
# 36
其中 return head + sum(tail) if tail else head 的意思是:
if tail:
    return head + sum(tail)
else:
    return head
但是注意,递归不是 Python 的强项,这是因为其内在的递归限制所致,因此最后一个例子在实践中没有太大意义。

猜你喜欢

转载自www.linuxidc.com/Linux/2017-08/146174.htm
今日推荐