每日一课 | python 元组解构赋值
下一版的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
今日福利????
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
