Python- learning the basics of tuples (tuple)

Tuple (tuple): This is a fixed length, immutable sequence of objects. Representation:

tup = 4,5,6

print(tup)

#会看到打印
(4, 5, 6)

Tuple may further comprise a tuple of tuples, such as:

nested_tup = (4, 5, 6), (7, 8)

print(nested_tup)

#打印结果
((4, 5, 6), (7, 8))

In actual use, often we need to be converted into an array or a tuple into a tuple string conversion, so that each can access data directly or letters, such as:

tup = tuple([1, 2, 3])

print(tup)

#打印出
(1, 2, 3)


tup = tuple('hello')

print(tup)

#打印
('h', 'e', 'l', 'l', 'o')

#如果通过下标访问,就能拿到下标对应的字母了
print(tup[0])

#打印
'h'

Speaking above we tuple fixed length sequence of objects can not be changed, if the tuple object contains an array or other objects, the object can be changed to the internal data, such as:

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

tup[1].append(3)

print(tup)

#打印
('foo', [1, 2, 3], True)

Tuple may also be used '+' sign splicing:

tup1 = (1, 2, 3)
tup2 = (5, 6)
tup3 = ('hello', 'world')

tup = tup1 + tup2 + tup3

print(tup)

#打印
(1, 2, 3, 5, 6, 'hello', 'world')

Tuples and integer multiplication, doubling the result is the tuple:

tup = (1, 2) * 4

print(tup)

#打印
(1, 2, 1, 2, 1, 2, 1, 2)

#注意,对象自身并没有复制,只是指向它们的引用进行了复制。

In everyday use, there is a very important function, that is, tuple unpacking, such as:

tup = (1, 2, 3)

a, b, c = tup

print(a)

#打印
1

#另外一种情况,嵌套元组拆包:
tup = 1, 2, (3, 4)

a, b, (c, d) = tup

print(c)

#打印
3

Through the above unpacking, it can be very simple to do the data exchange:

a, b = 1, 2

print(a, b)
#打印
1, 2

#对两个变量的数据进行交换
b, a = a, b

print(a, b)
#打印
2, 1

#这样可以很容易做到交换了,而不需要第三个临时变量保存数据

Finally, in terms of writing a Python function, often we need to return multiple results, we can use tuples:

#从一系列数据中找到最大值和最小值并且返回
def func_max_min(a, b, c, d):
    fmax = max(a, b, c, d)
    fmin = min(a, b, c, d)
    return (fmax, fmin)

Only one method of tuples is count, which it can count the number of elements in the tuple:

tup = (1, 2, 2, 2, 3, 4, 5, 2)

print(tup.count(2))

#打印
4

 

Guess you like

Origin blog.csdn.net/pz789as/article/details/93724476