zoukankan      html  css  js  c++  java
  • 『Python CoolBook』数据结构和算法_多变量赋值&“*”的两种用法

    多变量赋值

    a = [1,2,(3,4)]
    b,c,d = a
    print(b,c,d)
    b,c,(d,e) = a
    print(b,c,d,e)
    
    1 2 (3, 4)
    1 2 3 4
    a = "zxc"
    b,c,d = a
    print(b,c,d)
    

    z x c 

    *:集成不定长元素 & 集合型实参展开为多个虚参

    record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
    name, email, *phone_numbers = record
    
    name,email,phone_numbers
    

     ('Dave', 'dave@example.com', ['773-555-1212', '847-555-1212'])

    注意,

    1. *后修饰的变量无论接收元素多少,一定会返回list数据结构。
    2. *也可以放在函数实参处,此时会将list的元素展开分别赋值于各个虚参;和上面集成多元素为list相反,此时表示将list展开将元素赋值于多变量。
    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
    
  • 相关阅读:
    全文本搜索神器
    唯一索引和普通索引怎么选择
    程序员应不应该搞全栈
    c 的陷阱
    抽象能力
    电影电视剧推荐
    系统故障诊断
    一次web网站被入侵的处理记录
    Spark RDD 操作
    (转)Mysql哪些字段适合建立索引
  • 原文地址:https://www.cnblogs.com/hellcat/p/8565817.html
Copyright © 2011-2022 走看看