python cookbook第一章

    xiaoxiao2021-03-25  77

    解压序列赋值给多个变量

    '''使用无关变量,如_或者ign''' data = ['ACME', 50, 91.1, (2017, 2, 27)] _, shares, price, _ = data print(shares) print(price) ''' 50 91.1 ''' ''' 使用*号 ''' record = ('Dave', 'dave@example.com', '110', '120') name, email, *phone_numbers = record print(name) print(email) print(phone_numbers) ''' 'Dave' 'dave@example.com' ['110', '120'] ''' sales_record = [1, 2, 3, 4, 5, 6, 7] *trailing_qtrs, current_qtr = sales_record trailing_avg = sum(trailing_qtrs) / len(trailing_qtrs) print(trailing_avg) ''' >>>3.5 ''' '''星号表达式迭代可变长元组''' records = [ ('foo', 1, 2), ('bar', 'hello'), ('foo', 3, 4) ] for tag, *args in records: print(args) ''' [1, 2] ['hello'] [3, 4] ''' '''字符串操作''' line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/user/bin/false' uname, *fields, homedir, sh = line.split(':') print(uname) print(fields) print(homedir) print(sh) ''' nobody ['*', '-2', '-2', 'Unprivileged User'] /var/empty /user/bin/false ''' record = ('ACME', 50, 123.45, (12, 18, 2015)) name, *_, (*_, year) = record print(name) print(year) ''' ACME 2015 ''' '''使用这样的分割语法实现递归''' items = [1, 2, 3, 4, 5, 6, 7] def my_sum(items): head, *tail = items return head + sum(tail) if tail else head print(my_sum(items)) ''' >>>28 '''
    转载请注明原文地址: https://ju.6miu.com/read-17367.html

    最新回复(0)