每日一课 | python 元组解构赋值

it2025-06-03  8

下一版的Ceylon具有一系列有趣的新语言功能,包括构造函数, if和switch表达式, let和object表达式,以及对元组和条目的解构 。在这篇文章中,我将描述用于解构的新语法。

解构语句看起来很像普通的值声明,只是我们希望看到值名称的地方出现了模式 。

使用瘦箭头指示输入模式->我们用来构造条目:

String->Integer entry = "one"->1; value key->item = entry; //destructure the Entry

元组模式用括号指示:

[String,Integer] pair = ["one",1]; value [first,second] = pair; //destructure the Tuple

模式变量 , key , item , first和second只是常规局部值。

我们可以嵌套元组和进入模式:

String->[String,Integer] entry = "one"->["one",1]; value key->[first,second] = entry;

元组模式可以具有尾部变量,用*表示:

[String+] ints = 1..100; value [first,*rest] = ints; //destructure the Sequence

(此语法类似于传播运算符。)

模式可以选择指示显式类型:

value String key->[String first, Integer second] = entry;

基于模式的解构可以在该语言的许多其他地方发生。模式可以出现在for循环中:

if (exists index->item = stream.indexed.first) { ... }  if (nonempty [first,*rest] = sequence) { ... }

或exists或非nonempty情况下:

if (exists index->item = stream.indexed.first) { ... }  if (nonempty [first,*rest] = sequence) { ... }

或在let表达式中:

value dist = let ([x,y] = point) sqrt(x^2+y^2);

翻译自: https://www.javacodegeeks.com/2014/12/tuple-and-entry-destructuring.html

今日福利????

最新回复(0)