元组
python的元组与列表类似,不同之处在于元组的元素不能修改,元组使用小括号,列表使用方括号,元组声明后,长度就固定了。
In [1]: my_strs=("a","bbb",'ccc') In [2]: my_strs Out[2]: ('a', 'bbb', 'ccc') In [3]: my_strs[0] Out[3]: 'a' In [4]: my_strs[-1] Out[4]: 'ccc' In [5]: my_strs[3] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-5-978c5894f0f0> in <module>() ----> 1 my_strs[3] IndexError: tuple index out of range In [6]: my_strs[0]="aaa" --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-4152d9453e33> in <module>() ----> 1 my_strs[0]="aaa" TypeError: 'tuple' object does not support item assignment In [8]: len(my_strs) #定义好了元组,长度就固定了。 Out[8]: 3 In [11]: name=[1,2,3,4] In [12]: my_tuple=(100,200,name) #元组中的元素为列表 In [13]: my_tuple Out[13]: (100, 200, [1, 2, 3, 4]) In [15]: my_tuple[2] Out[15]: [1, 2, 3, 4] In [16]: my_tuple[2][0]=100 #元组中若包含列表,列表本身是可以修改的。 In [17]: my_tuple Out[17]: (100, 200, [100, 2, 3, 4])
元组没有增删改,只有查操作内置函数index, count ,in, not in
In [17]: my_tuple Out[17]: (100, 200, [100, 2, 3, 4]) In [19]: my_tuple.index(100) Out[19]: 0 In [20]: my_tuple.count(100) Out[20]: 1 In [21]: 100 in my_tuple Out[21]: True In [22]: 100 not in my_tuple Out[22]: False In [23]: