1. 程式人生 > 其它 >Python Tip4:python中的元組操作詳解

Python Tip4:python中的元組操作詳解

技術標籤:Python Tips元組tuple列表資料結構python

本文源自微信公眾號 Python客棧,原文連結:10個示例帶你掌握python中的元組 如有侵權,聯絡必刪

Python資料型別之:元組

元組是Python的一種非常重要的資料結構,用逗號把資料隔開,用小括號括起來。

常常拿元組與列表作對比,他倆相似,都是值的集合,最大的區別應該就是 列表是可變型別,元組是不可變型別

1. 建立元組:

  • 元組由括號中的值組成,並用逗號分隔開
>>> a = (1, 2, 3)
>>> a
(1, 2, 3)
>>> type(a)
<class 'tuple'>
  • 元組可以儲存不同資料型別的值和重複值
>>> b = ([1, 2, 3], 4, 4)
>>> b
([1, 2, 3], 4, 4)
>>> type(b)
<class 'tuple'>
  • 可以不加括號建立元組,用逗號分隔開,就是元組格式
>>> c = 1, 2, 3
>>> c
(1, 2, 3)
>>> type(c)
<class 'tuple'>

2. 建立沒有元素或只有1個元素的元組

  • 建立沒有元素的空元素
>>> d = ()
>>> d
()
>>> type(d)
<class 'tuple'>
  • 建立具有1個元素的元組,需要在元素後面加上逗號,否則當做元素的普通變數型別處理
>>> e = (1)
>>> e
1
>>> type(e)
<class 'int'>
>>> f = ([1, 2, 3])
>>> f
[1, 2, 3]
>>> type(f)
<class 'list'>
  • 正確的建立方法
>>> g = (1,)
>>> g
(1,)
>>> type(g)
<class 'tuple'>
>>> h = ({1, 2, 3},)
>>> h
({1, 2, 3},)
>>> type(h)
<class 'tuple'>

3. 元組是可迭代的

  • 跟列表一樣,可以使用for迴圈進行遍歷
>>> i = (1, 2, 3, 4, 5)
>>> for value in i:
		print(value ** 2)
	
1
4
9
16
25
>>> j = (1, 2, [3, 4], 'aaa')
>>> for value in j:
		print(value)
	
1
2
[3, 4]
aaa

4. 元組元素的訪問

  • 利用下標索引訪問
>>> k = (1, 2, 3, ['a', 'b', 123], '55')
>>> k[2]
3
>>> k[-1]
'55'
  • 利用切片訪問
>>> l = ([1, 2, 3], 'aa', {'name':'Jason'}, 4, 44)
>>> l[2:]
({'name': 'Jason'}, 4, 44)
>>> l[:3]
([1, 2, 3], 'aa', {'name': 'Jason'})

5. 元組當前存放的元素是不可變的,但是可以具有可變元素

  • 不變性可能是元組最具有識別性的特徵。我們不能修改元組中的元素。
>>> m = (1, 2, 3)
>>> m[1] = 4
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    m[1] = 4
TypeError: 'tuple' object does not support item assignment
  • 但是,元組可以包含可變元素,例如列表。
>>> n = ([1, 2, 3], ['a', 5])
>>> n[0]
[1, 2, 3]
>>> n[0][1]
2
>>> n[1][0]
'a'

6. 元組的排序

  • 元組當前存放的元素是不可變的,無法用sort進行排序
>>> o = (11, 2, 9, 3)
			   
>>> o.sort()
			   
Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    o.sort()
AttributeError: 'tuple' object has no attribute 'sort'
  • 但是sorted可以將元組作為引數,並返回一個已經排序好的列表,注意,返回的是一個排序好的列表而不是一個排序好的元組。
>>> p = (20, 4, 2, 9, 14)
>>> q = sorted(p)
>>> q
[2, 4, 9, 14, 20]
>>> type(q)
<class 'list'>

sorted

7. 元組的常用函式

  • len() 獲取元組長度
>>> len((1, 2, 3))
3
  • max(),min()返回元組中元素的最大,最小值
>>> r = (2, 1, 0, -4, 6)
>>> max(r)
6
>>> min(r)
-4
 - 要求元組中必須是同一種資料型別(不一定是數字,字串也可以)
 - 有個有意思的是:
>>> a = (' ', 'a', 'bb', 'c', '')
>>> min(a)
''
>>> max(a)
'c'
  • tuple()用於將列表轉換為元組
>>> s = [2, 'a', [1, 2]]
>>> tuple(s)
(2, 'a', [1, 2])
>>> type(s)
<class 'list'>
>>> s = [2, 'a', [1, 2]]
>>> t = tuple(s)
>>> t
(2, 'a', [1, 2])
>>> type(t)
<class 'tuple'>

8. count()和index()

  • count() 獲取元組中某個值出現的次數
>>> u = (1, 2, 3, 2, 2, 'a')
>>> u.count(2)
3
>>> u.count(8)  # 沒有該元素不會報錯,而是返回0
0
  • index()可以用來返回元組中元素的下標索引
>>> v = (1, 2, 3, 2, 2, 'a')
>>> v.index(2)  # 含多個值,會取最先出現的值的下標
1
>>> v.index('a')
5

9. 拼接元組

  • 利用"+"可以把兩個元組拼接起來組成一個
>>> w = (1, 2, 3)
>>> x = ('a', 'b', '5')
>>> w + x
(1, 2, 3, 'a', 'b', '5')
>>> y = (['a', '11'],)
>>> w + y
(1, 2, 3, ['a', '11'])

10. 用元組讓函式返回多個值

一般一個函式只能有一個返回值。我們可以用元組讓函式返回多個值:

  • 以下函式接受一個數組,並返回該陣列的總和sum與陣列長度count。
def sum_count(attr):
	sum = attr.sum()
	count = len(attr)
	return sum, len
  • 下面函式是返回的是具有2個專案的元組:
import numpy as np

attr = np.random.randint(10, size=8)


def sum_count(attr):
    ''' 返回具有2個專案的元組 '''
    sum = attr.sum()
    count = len(attr)
    return sum, count


sc = sum_count(attr)
print(sc)
# (53, 8)
print(type(sc))
# <class 'tuple'>