005: 基本数据类型-Tuple

Tuple 可以理解为数组,初始化之后数组本身便不可更改。它是一种表示序列化数据的数据类型,目前只做初步学习,以后再做更深入的了解。

Tuples may be constructed in a number of ways:

  1)Using a pair of parentheses to denote the empty tuple: ()

  2)Using a trailing comma for a singleton tuple: a, or (a,)

  3)Separating items with commas: a, b, c or (a, b, c)

  4)Using the tuple() built-in: tuple() or tuple(iterable)

The constructor builds a tuple whose items are the same and in the same order as iterable‘s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example, tuple('abc') returns ('a', 'b', 'c') and tuple( [1, 2, 3] ) returns (1, 2, 3). If no argument is given, the constructor creates a new empty tuple, ().

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, f(a, b, c) is a function call with three arguments, while f((a, b, c)) is a function call with a 3-tuple as the sole argument.

因为tuple是一个序列类型,所以支持用下标来访问:

x = 1, 2, 3, 4, 5
x[0] # 1

可以一次性把元组里面的值,赋给多个变量:

stock = ('002582', 28.10, 28.80, 28.90, 28.00)
code, open_price, close_price, high, low = stock
# 依次赋值, code 为 '002582', open_price 为 28.10

也可以定义命名元组:

from collections import namedtuple
# this method would return a new type of Stock which is the subclass of tuple Stock
= namedtuple('Stock', 'symbol price') stock = Stock ('0022582', 28.10) stock.symbol

今天的一些练习:

tuple_a = 1,3,5,7,9,11
tuple_b = 'hello', 'world'
tuple_c = 'hello',
tuple_d = tuple('hello')
tuple_e = ()
tuple_f = (1,3,5,7,9,11,13,15)
tuple_g = tuple('abc')
tuple_h = tuple([1,3,5,7])

tuple_x, tuple_y, tuple_z = (2,4,(8,16))

print('tuple_a =',tuple_a)
print('len(tuple_a) =',len(tuple_a))
print('tuple_a[1] =',tuple_a[1])
print('tuple_b =',tuple_b)
print('tuple_c =',tuple_c)
print('tuple_d =',tuple_d)
print('tuple_e =',tuple_e)
print('tuple_f =',tuple_f)
print('tuple_g =',tuple_g)
print('tuple_h =',tuple_h)
print('tuple_x =',tuple_x)
print('tuple_y =',tuple_y)
print('tuple_z =',tuple_z)

list_a = [1,3,5]
tuple_i = tuple(list_a)
print('list_a =',list_a)
print('tuple_i =',tuple_i)
list_a.append(7)
print('list_a =',list_a)
print('tuple_i =',tuple_i)

运行结果如下:

tuple_a = (1, 3, 5, 7, 9, 11)
len(tuple_a) = 6
tuple_a[1] = 3
tuple_b = ('hello', 'world')
tuple_c = ('hello',)
tuple_d = ('h', 'e', 'l', 'l', 'o')
tuple_e = ()
tuple_f = (1, 3, 5, 7, 9, 11, 13, 15)
tuple_g = ('a', 'b', 'c')
tuple_h = (1, 3, 5, 7)
tuple_x = 2
tuple_y = 4
tuple_z = (8, 16)
list_a = [1, 3, 5]
tuple_i = (1, 3, 5)
list_a = [1, 3, 5, 7]
tuple_i = (1, 3, 5)

原文地址:https://www.cnblogs.com/jcsz/p/5099062.html