# （Python基础教程之九）Python中的Tuple操作

2020.05.08 07:50 710浏览

Pyhton中元组类似于不变，list但不可变，并带有可选的圆括号

• 不可变
• 有序
• 异质
• 索引（从零开始）
• 带圆括号（可选，但建议）
• 在迭代过程中更快，因为它是不可变的

## 1. Creating a Tuple

``````Tuple = (item1, item2, item3)
``````

``````tuple1 = () # empty tuple

tuple2 = (1, "2", 3.0)

tuple3 = 1, "2", 3.0
``````

#### 1.1. Tuple with one element

``````tupleWithOneElement = ("hello", ) # Notice trailing comma
``````

#### 1.2. Nested Tuple

``````nestedTuple = ("hello", ("python", "world"))
``````

## 2. Accessing Tuple Items

• 正索引从元组的开始开始计数。
• 负索引从元组的末尾开始计数。
• 一定范围的索引将使用指定的项目创建一个新的元组（称为Slicing）。
• 范围[m:n]是指从位置m（）到位置n（不含）。
• 使用双索引访问嵌套元组的元素。

``````Tuple = ("a", "b", "c", "d", "e", "f")

print(Tuple[0]) # a

print(Tuple[1]) # b

print(Tuple[-1]) # f

print(Tuple[-2]) # e

print(Tuple[0:3]) # ('a', 'b', 'c')

print(Tuple[-3:-1]) # ('d', 'e')

Tuple = ("a", "b", "c", ("d", "e", "f"))

print(Tuple[3]) # ('d', 'e', 'f')

print(Tuple[3][0]) # d

print(Tuple[3][0:2]) # ('d', 'e')
``````

## 3. Loop into tuple

``````Tuple = ("a", "b", "c")

for x in Tuple:

print(x)
``````

## 4. Check if an item exist in tuple

``````Tuple = ("a", "b", "c", "d", "e", "f")

if "a" in Tuple:

print("Yes, 'a' is present") # Yes, 'a' is present

if "p" not in Tuple:

print("No, 'p' is not present") # No, 'p' is not present
``````

## 5. Sorting a Tuple

``````Tuple = ("a", "c", "b", "d", "f", "e")

sortedTuple = sorted(Tuple)

print (sortedTuple) # ("a", "b", "c", "d", "e", "f")
``````

## 6. Repetition and Concatenation of Tuples

``````Tuple = ("a", "b")

repeatedTuple = Tuple * 3

print (repeatedTuple) # ('a', 'b', 'a', 'b', 'a', 'b')
``````

``````Tuple1 = ("a", "b", "c")

Tuple2 = ("d", "e", "f")

joinedTuple = Tuple1 + Tuple2

print (joinedTuple) # ("a", "b", "c", "d", "e", "f")
``````

## 7. Packing and Unpacking the Tuple

Packing

``````Tuple = ("a", "b", "c")
``````

Unpacking

``````Tuple = ("a", "b", "c") # Packing

(x, y, z) = Tuple

print (x) # a

print (y) # b

print (z) # c
``````

Unpacking errors

``````Tuple = ("a", "b", "c") # Packing

(x, y, z) = Tuple       # ValueError: too many values to unpack (expected 2)

(x, y, z, i) =  Tuple   # ValueError: not enough values to unpack (expected 4, got 3)
``````

## 8. Named tuples

Python提供了一种来自模块的特殊类型的函数，名为**namedtuple（）**collection。

``````import collections

Record = collections.namedtuple('Record', ['id', 'name', 'date'])

R1 = Record('1', 'My Record', '12/12/2020')

#Accessing using index

print("Record id is:", R1[0]) # Record id is: 1

# Accessing using key

print("Record name is:", R1.name) # Record name is: My Record
``````

## 9. Python Tuples Methods

#### 9.1. any()

``````print( any( () ) ) # Empty tuple - False

print( any( (1,) ) ) # One element tuple - True

print( any( (1, 2) ) ) # Regular tuple - True
``````

#### 9.2. min()

``````Tuple = (4, 1, 2, 6, 9)

print( min( Tuple ) ) # 1
``````

#### 9.3. max()

``````Tuple = (4, 1, 2, 6, 9)

print( max( Tuple ) ) # 9
``````

#### 9.4. len()

``````Tuple = (4, 1, 2, 6, 9)

print( len( Tuple ) ) # 5
``````

#### 9.5. sum()

``````Tuple = (4, 1, 2, 6, 9)

print( sum( Tuple ) ) # 22
``````

1人点赞

• 1
• 评论
• 收藏
• 共同学习，写下你的评论

0/150