zoukankan      html  css  js  c++  java
  • Python实用黑科技——解包元素(2)

    需求:
    前面的文章讲的是使用变量的个数需要和迭代器数据变量的元素个数相同的方法,但更多的时候确实不想根据元素个数n来定义相应多的变量,而是希望用较少的变量(

    def drop_first_last(grades):
    def avg(my_list):
    return sum(my_list) / len(my_list)
    first, *middle, last = sorted(grades)
    return avg(middle)
    1
    2
    3
    4
    5
    当然,“星表达式”可以在任何位置,对应的解包元素存入之后,都会形成一个列表(即使没有对应元素,也是空列表)。这里可以再想像一个例子,你正在查看自己近1整年的工资流水,你想计算一下前11个月的工资平均值和当月的工资进行比较,自然可以这么做:

    salary_record = (9000, 9000, 12000, 9000, 7000, 8000, 9000, 9000,
    10000, 10000, 8500, 10500)
    *trailing_months, current_month = salary_record
    trailing_avg = sum(trailing_months) / len(trailing_months)
    result = current_month > trailing_avg
    1
    2
    3
    4
    5
    扩展:
    上面举的例子也许会让读者觉得多此一举,毕竟无论是元组还是列表,用更多其他方式来获取相应的结果,比如第一个可以直接这么获取:

    middle_avg = sum(sorted(grades)[1 : len(grades) - 1]) / (len(grades) - 2)
    1
    当然还有很多办法,这就看大家觉得用什么方式实现更好的表达自己思想了。此外,“星表达式”对处理一种含有多个长度不等元组组成的列表的数据,有他自己独特的优势:

    records = [
    ('Jason', 'SE', 6),
    ('Lee', 'Python'),
    ('Jason', 'Web', 2),
    ]

    def show_jason(x, y):
    print('Jason', x, y)

    def show_lee(s):
    print('Lee', s)

    for tag, *args in records:
    if tag == 'Jason':
    show_jason(*args)
    elif tag == 'Lee':
    show_lee(*args)

    In [67]: runfile('/home/jason/codes/test.py', wdir='/home/jason/codes')
    Jason SE 6
    Lee Python
    Jason Web 2
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    这里还可以举一个求列表元素和的有趣的递归方法:

    def sum(items):
    head, *tail = items
    return head + sum(tail) if tail else head

    sum(range(10))
    Out[71]: 45
    1
    2
    3
    4
    5
    6
    当然,大家都懂得,递归从来都不是一个解决问题的好办法,所以看看也就行了。
    ————————————————
    版权声明:本文为CSDN博主「哈北儿」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/skysword_li/article/details/77618926

  • 相关阅读:
    QQ家园熄灭不了解决方法
    那时我们还年轻[转]
    QQ游戏图标熄灭大全
    FlashDevelop快捷键
    linux 全局搜索某一文件并将文件内容并进行替换的命令
    navigate 10.0.5 regist cn
    线程、socket、stl 以及并发设计
    drupal真不错
    网卡问题解决思路linux版
    socket错误:Program received signal SIGPIPE, Broken pipe
  • 原文地址:https://www.cnblogs.com/valorchang/p/11475724.html
Copyright © 2011-2022 走看看