《Beginning Python From Novice to Professional》学习笔记四:Tuple

来源:互联网 发布:js获取input file值 编辑:程序博客网 时间:2024/04/27 07:48
Tuple与List最大的区别就是Tuple的元素不可更改(和String一样),其它几乎感觉不到区别(The only difference is that tuples can’t be changed.

1.元素后出现逗号就自动成为Tuple
1,2,3 ---> (1,2,3)
(1,2,3) ---> (1,2,3)
18, ---> (18,)  #仅有一个元素
注意以下两例的区别:
3*(40+2) ---> 126
3*(40+2,) ---> (42, 42, 42)

2.Tuple转换
tuple([1, 2, 3]) ---> (1, 2, 3)
tuple('abc') ---> ('a', 'b', 'c')
tuple((1, 2, 3)) ---> (1, 2, 3)

小结,使用Tuple的两种可能:作为mapping的keys;以及作为内置函数的返回值。In general, lists will probably be adequate for all your sequencing needs.