python-进阶教程-数据结构的分解

0.摘要

本文主要介绍python中常用数据结构的分解方法。

1.可迭代对象分解为多个变量

任何可迭代对象都可以通过简单的赋值操作分解为单独的变量,唯一的要求是变量的总数和结构要与可迭代对象相吻合。

数量不匹配会报错。

data = [2018,'December',6,'Thursday']
year, month, day, weekday = data
print(year,month,day,weekday)
#result:2018 December 6 Thursday

字符串也是可迭代对象,所以按照上述说法,字符串也是可以拆分的:

s = "Hello"
a, b, c, d, e = s
print(a,b,c,d,e)
#result:H e l l o

 这里介绍一个技巧:对于不想保存的变量,可以将其赋值给一个不会用到的变量名。注意,要确保这个变量名在程序中是不会被用到的。通常情况,使用"_"保存想要丢弃的变量。

text = ['start','text1','text2','text3','end']
_, text1, text2, text3, _ = text
print(text1, text2, text3)

2. 任意长度的可迭代对象

在上一节中提到,可迭代对象分解的条件为:变量的总数和结构要与可迭代对象相吻合

如果分解的值过少,会报出:need more values to unpack 的错误;

如果分解的值过多,会报出:too many values to unpack 的错误。

对于数量不确定问题,可以尝试使用“*表达式”解决,“*表达式”能够匹配任意数量的变量。

group = ["tomato omelette", "tomato", "egg", "salt", "peanut oil",10.0 ]
dish, *ingredient, price= group
print(ingredient)
#result:['tomato', 'egg', 'salt', 'peanut oil']

可见,“*表达式”能够根据前后变量数目,自适应匹配分解的变量数。

另外,“*表达式”还可以列表切分:

sales_record = [10,9,10,11,8,15,12,6,18]
*trailing_qtrs, current_qrt = sales_record
trailing_avg = sum(trailing_qtrs) / len(trailing_qtrs)
print(trailing_avg,current_qrt)
#result:10.125 18

通过“*表达式”,我们将数据分为历史数据和当前数据两部分,当然这与sales_record[:-1],sales_record[1]效果是一样的。

利用这一点,可以实现精巧的递归结构:

items = [1,2,3,4,5,6,7,8,9,10]
def sum(items):
    head, *tail = items
    return head + sum(tail) if tail else head
print(sum(items))

另外,“*表达式”在迭代一个变长的元组序列时候尤其有用,例如:

def my_add(x,y):
    return x + y

def my_square(x):
    return x ** 2

orders = [
    ("add",1,2),
    ("square",3),
    ("add",4,5)
]

for tag, *args in orders:
    if tag == "add":
        print(my_add(*args))
    elif tag == "square":
        print(my_square(*args))

*args对一些带有默认参数值进行封装的时候非常有用,这可以使得我们不会被接口参数的数量问题所困扰。

猜你喜欢

转载自blog.csdn.net/qq_17753903/article/details/84865748