python3之元组
tuple
特性:
a. 元组是另一种有序的列表
b. list非常相似,但是tuple一旦创建,就不能修改
1.语法和list 类似,可以根据索引取值
In [86]: t = (‘wd‘,‘pc‘,‘lp‘,‘woniu‘) In [87]: t1 = tuple(‘abc‘) In [88]: t Out[88]: (‘wd‘, ‘pc‘, ‘lp‘, ‘woniu‘) In [89]: t1 Out[89]: (‘a‘, ‘b‘, ‘c‘) In [90]: print(t[0]) wd In [91]: print(t1[0]) a
2.创建一个单元素tuple
In [92]: t = () In [94]: print(t) () In [95]: type(t) Out[95]: tuple In [96]: t = (1) In [97]: type(t) Out[97]: int In [98]: print(t) 1
3.可变tuple
In [99]: t = (1,2,[3,4]) In [100]: t1 = t[2] In [101]: t1 Out[101]: [3, 4] In [102]: t1[0]=5 In [103]: t Out[103]: (1, 2, [5, 4]) In [104]: t1 Out[104]: [5, 4]
复制和引用
In [105]: l = [1,2,3,4] In [106]: l1 = l In [107]: l Out[107]: [1, 2, 3, 4] In [108]: l1[0]=5 In [109]: l1 Out[109]: [5, 2, 3, 4] In [110]: l Out[110]: [5, 2, 3, 4]
注意:
元组存在的意义,有很大一部分是因为,由于它的不可变,可以当做映射的key值,但是list就不不行
本文出自 “linux” 博客,请务必保留此出处http://liunxbk.blog.51cto.com/8683822/1750758
原文地址:http://liunxbk.blog.51cto.com/8683822/1750758