Home >> Blog >> Python tuple 元組基本語法概述

Python tuple 元組基本語法概述

在執行SEO優化過程中,我們常會使用Python tuple 元組基本語法。元組是有序且不可變的對象的集合。元組是序列,就像列表一樣。元組和列表之間的區別在於,元組不能更改,不像列表和元組使用括號,而列表使用方括號。

創建一個元組就像放置不同的逗號分隔值一樣簡單。或者,您也可以將這些逗號分隔的值放在括號之間。例如 -

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

空元組寫成兩個括號,不包含任何內容 -

tup1 = ();

要編寫一個包含單個值的元組,您必須包含一個逗號,即使只有一個值 -

tup1 = (50,);

像字符串索引一樣,元組索引從 0 開始,它們可以被切片、連接等等。

訪問元組中的值

要訪問元組中的值,請使用方括號進行切片以及索引或索引以獲得該索引處可用的值。例如 -

#!/usr/bin/python

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];

執行上述代碼時,會產生以下結果 -

tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

更新元組

元組是不可變的,這意味著您不能更新或更改元組元素的值。您可以使用現有元組的一部分來創建新元組,如下例所示 -

#!/usr/bin/python

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

# Following action is not valid for tuples
# tup1[0] = 100;

# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;

執行上述代碼時,會產生以下結果 -

(12, 34.56, 'abc', 'xyz')

刪除元組元素

無法刪除單個元組元素。當然,將另一個元組與丟棄的不需要的元素放在一起並沒有錯。/p>

要顯式刪除整個元組,只需使用del語句。例如 -

#!/usr/bin/python

tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;

這會產生以下結果。注意引發異常,這是因為在del tup 元組之後不再存在 -/p>

('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in
print tup;
NameError: name 'tup' is not defined

基本元組操作

元組對 + 和 * 運算符的響應很像字符串;他們在這裡也意味著連接和重複,除了結果是一個新的元組,而不是一個字符串。

事實上,元組響應我們在前一章中對字符串使用的所有一般序列操作 -

索引、切片和矩陣

因為元組是序列,所以索引和切片對元組的工作方式與對字符串的工作方式相同。假設以下輸入 -

L = ('spam', 'Spam', 'SPAM!')

沒有封閉分隔符

任何一組多個對象,逗號分隔,不帶識別符號,即列表的括號,元組的括號等,默認為元組,如這些簡短的示例所示 -

#!/usr/bin/python

print 'abc', -4.24e93, 18+6.6j, 'xyz';
x, y = 1, 2;
print "Value of x , y : ", x,y;/p>

執行上述代碼時,會產生以下結果 -

abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2

內置元組函數

Python 包括以下元組函數 -

tuple

tuple

教程

learn

list

template

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

tuple

matplotlib

java

tutorial

jquery

range

range

number

css

中文

course