1.1 Data structure and sequence
1.1.1 tuple
Tuple is a fixed length, python target sequence immutable.
In [1]: tup = 4, 5, 6 In [2]: tup Out[2]: (4, 5, 6)
It may be generated tuples of tuples
In [3]: nested_tup = (4, 5, 6), (7, 8) In [4]: nested_tup Out[4]: ((4, 5, 6), (7, 8))
tuple function can convert any sequence or iterator tuple
In [5]: tuple([4, 0, 2]) Out[5]: (4, 0, 2) In [6]: tup = tuple('string') In [7]: tup Out[7]: ('s', 't', 'r', 'i', 'n', 'g')
Tuple may [] be obtained by brackets, python sequence index is started from 0
In [9]: tup[0] Out[9]: 's'
Although tuple of objects stored in the object itself is variable, but tuples Once created, all objects on various locations and can not be modified.
In [10]: tup = tuple(['foo', [1, 2], True]) In [11]: tup[2] = False --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-11-b89d0c4ae599> in <module> ----> 1 tup[2] = False TypeError: 'tuple' object does not support item assignment
If an object in a tuple is variable, for example, a list may be modified within the
In [12]: tup[1].append(3) In [13]: tup Out[13]: ('foo', [1, 2, 3], True)
+ Can be used to connect the longer tuples generated tuple
In [14]: (4, None, 'foo') + (6, 0) + ('bar',) Out[14]: (4, None, 'foo', 6, 0, 'bar')
1.1.1.1 tuple unpacking
If you want to assign a tuple type of expression to a variable, python will value the right of the equal sign unpacking
In [15]: tup = (4, 5, 6) In [16]: a, b, c = tup In [17]: b Out[17]: 5
Even unpacking may be nested tuple
In [18]: tup = 1, 2, (3, 4) In [19]: a, b, (c, d) = tup In [20]: c Out[20]: 3
Unpacking a common scenario is to traverse the list of tuples or consisting of the sequence
In [21]: seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] In [22]: 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
There are some more advanced python tuple unpacking features, such as syntax * rest for any length of time to obtain a list of positional parameters function call
In [23]: values = 1, 2, 3, 4, 5 In [24]: a, b, *rest = values In [25]: a, b Out[25]: (1, 2) In [26]: rest Out[26]: [3, 4, 5]
Sometimes rest is part of the data you want to discard, rest variable name itself has no special meaning, usually in order to facilitate the use of an underscore _ to represent the unwanted variables
In [27]: a, b, *_ = values
1.1.1.2 tuple method
Since the content and length of the tuple is not changed, its instances method is rarely. A common method is useful to count (list is also available), a measurement of the number of times the value appears in a tuple
In [28]: a = (1, 2, 2, 2, 4, 3, 2) In [29]: a.count(2) Out[29]: 4