Python - 从数组中提取元素,类似于 JavaScript ES6 解构

Ben*_*enB 1 javascript python arrays dictionary

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

const [first, second] = names;  
console.log(first, second); // 'Luke' 'Eva'  
Run Code Online (Sandbox Code Playgroud)

python 有类似的语法吗?

Ism*_*lla 6

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

myList = [1, 2, 3]
a, b, c = myList
print(a) # 1
print(b) # 2
print(c) # 3
Run Code Online (Sandbox Code Playgroud)

另外,在 javascript 中你可以执行以下操作:

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

这在Python中也可以实现:

myList = [1, 2, 3]
first, *other = myList
print(first) # 1
print(other) # [2, 3]
Run Code Online (Sandbox Code Playgroud)

以下也是可能的:

myList = [1, 2, 3, 4, 5]
a, *other, last = myList
print(a)      # 1
print(other)  # [2, 3, 4]
print(last)   # 5
Run Code Online (Sandbox Code Playgroud)

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

a, b, *other = (1, 2, 3, 4, 5)
print(a)     # 1
print(b)     # 2
print(other) # [3, 4, 5]
Run Code Online (Sandbox Code Playgroud)