利用Python进行数据分析

元组

2018-12-07  本文已影响15人  庵下桃花仙

逗号隔开

In [3]: tup = 4, 5, 6

In [4]: tup
Out[4]: (4, 5, 6)

In [5]: nested_tup = (4, 5, 6), (7, 8)

In [6]: nested_tup
Out[6]: ((4, 5, 6), (7, 8))

tuple函数将任意序列或迭代前转换为元组

In [7]: tuple([4, 0, 2])
Out[7]: (4, 0, 2)

In [8]: tup = tuplr('string')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-64894eb043d3> in <module>
----> 1 tup = tuplr('string')

NameError: name 'tuplr' is not defined

In [9]: tup = tuple('string')

In [10]: tup
Out[10]: ('s', 't', 'r', 'i', 'n', 'g')

In [11]: tup[0]
Out[11]: 's'
In [12]: tup = tuple('foo', [1,2], True)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-ec2d6fb5a293> in <module>
----> 1 tup = tuple('foo', [1,2], True)

TypeError: tuple expected at most 1 arguments, got 3

In [13]: tup = tuple(['foo', [1, 2], True])

In [14]: tup
Out[14]: ('foo', [1, 2], True)

In [15]: tup[2] = False
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-b89d0c4ae599> in <module>
----> 1 tup[2] = False

TypeError: 'tuple' object does not support item assignment

In [16]: tup[1].append(3)

In [17]: tup
Out[17]: ('foo', [1, 2, 3], True)
In [18]: (4, None, 'foo') + (6, 0) + ('bar',)
Out[18]: (4, None, 'foo', 6, 0, 'bar')

In [19]: ('foo', 'bar') * 4
Out[19]: ('foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar')

元组拆包

如果想将元组型表达式赋值给变量,Python会对等号右边的值进行拆包。

In [1]: tup = (4, 5, 6)

In [2]: a, b, c = tup

In [3]: b
Out[3]: 5

In [4]: tup = 4, 5, (6, 7)

In [5]: a, b, (c, d) = tup

In [6]: d
Out[6]: 7

In [7]: a, b = 1, 2

In [8]: a
Out[8]: 1

In [9]: b
Out[9]: 2

In [10]: b, a = a, b

In [11]: a
Out[11]: 2

In [12]: b
Out[12]: 1

拆包常用的场景:

1、遍历元组或列表组成的序列;
2、从函数返回多个值

In [13]: seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

In [14]: for a, b, c in seq:
    ...:     print('a = {0}, b = {1}, c = {2}'.format(a, b,c))
a = 1, b = 2, c = 3
a = 4, b = 5, c = 6
a = 7, b = 8, c = 9

从元组的起始位置采集一些元素。特殊语法*rest,用于在函数调用时获取任意长度的参数列表。

rest有时是想要丢掉的数据,rest这个变量名没有特别之处,有时用下划线表示不想要的量。

In [15]: values = 1, 2, 3, 4, 5

In [16]: a, b, *rest = values

In [17]: a, b
Out[17]: (1, 2)

In [18]: rest
Out[18]: [3, 4, 5]

In [19]: a, b, *_ = values

In [20]: a
Out[20]: 1

In [21]: b
Out[21]: 2

In [22]: a,b
Out[22]: (1, 2)

In [23]: _
Out[23]: [3, 4, 5]

元组方法

In [24]: a = (1, 2, 2, 2, 3, 4, 2)

In [25]: a.count(2)
Out[25]: 4
上一篇下一篇

猜你喜欢

热点阅读