python 元组的使用

0x00

简单📝一下。

0x01

  • 元组的元素不可改变,列表可以。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
In [1]: a = [1,2,3]                                                             

In [2]: a[0]=4

In [3]: print(a)
[4, 2, 3]

In [8]: b = (1,2,3)

In [9]: b[0]=4
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-07d5598ad652> in <module>
----> 1 b[0]=4

TypeError: 'tuple' object does not support item assignment
  • 当想创建只有一个元素的元组时,需要在元素后加上,
1
2
3
4
5
In [11]: (1)                                                                    
Out[11]: 1 # 这里是一个 int 类型

In [12]: (1,)
Out[12]: (1,) # 这里是一个 tuple 类型
  • 还有一种创建元组的方式 使用 tuple([iterable]) 传入一个迭代器 如果不传则返回一个空的元组
1
2
3
4
5
6
7
8
In [27]: tuple()                                                                
Out[27]: ()

In [28]: tuple('123')
Out[28]: ('1', '2', '3')

In [35]: tuple(['123','456','789'])
Out[35]: ('123', '456', '789')

0x02

封面出处:http://simpledesktops.com/browse/desktops/2015/sep/25/siri/

Author: ronething
Link: https://blog.ronething.cn/20190525-tuple-usage.html
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.