【问题标题】:Python - Extracting elements from an array similar to JavaScript ES6 DestructuringPython - 从类似于 JavaScript ES6 解构的数组中提取元素
【发布时间】:2020-01-08 17:30:35
【问题描述】:

使用 JavaScript ES6 语法,我可以从数组中设置变量:

const [first, second] = names;  
console.log(first, second); // 'Luke' 'Eva'  

python 有类似的语法吗?

【问题讨论】:

    标签: javascript python arrays dictionary


    【解决方案1】:

    是的,你可以像这样解压列表:

    myList = [1, 2, 3]
    a, b, c = myList
    print(a) # 1
    print(b) # 2
    print(c) # 3
    

    此外,在 javascript 中,您可以执行以下操作:

    // javascript:
    let myArray = [1, 2, 3];
    let [first, ...other] = myArray;
    console.log(first); // 1
    console.log(other); // [2, 3]
    

    这在 Python 中也可以实现:

    myList = [1, 2, 3]
    first, *other = myList
    print(first) # 1
    print(other) # [2, 3]
    

    以下也是可能的:

    myList = [1, 2, 3, 4, 5]
    a, *other, last = myList
    print(a)      # 1
    print(other)  # [2, 3, 4]
    print(last)   # 5
    

    它也适用于元组,但请注意,当使用 * 运算符解包元组时,结果是一个列表:

    a, b, *other = (1, 2, 3, 4, 5)
    print(a)     # 1
    print(b)     # 2
    print(other) # [3, 4, 5]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 2018-09-15
      相关资源
      最近更新 更多