首頁  >  文章  >  後端開發  >  python序列基礎--元組

python序列基礎--元組

巴扎黑
巴扎黑原創
2017-07-18 13:54:361425瀏覽

元組,跟列表一樣,屬於序列的一員,不同的是它是不可變序列 

元組的宣告:

1、空元組:()

2、1個成員的元組:(1,)或1,

3、多個成員:(1,2)或1,2 

註:宣告元組時,括號不是必須的,但逗號很重要,宣告1個成員的元組必須帶逗號 

tuple()方法

方法解釋:可以將其他序號轉成元組,用法和list()一致 

其他序列通用操作,詳見

基本功能的使用上,元組都可以被列表替代 

元組存在的意義:

1、元組可以在映射中作為鍵使用

2、元組被很多內建函數和方法作為返回值

 

元組

Tuples are immutable(=String), that means you can't do with tuples like this:

tuple.sort()  

tuple.append (5)  

tuple.reverse()   

這些都是自備的方法(像object.function這種形式的使用方法),將實際的改變自己。

逗號, 是tuple 的標誌:

x = 4,5,6  

print x  

#print 3*(40+2),3 *(40+2,)  


Tuple 的最大用途就是充當暫時的、長度固定的變數(就如同希望字典裡面的值按照value 而不是key 進行排序):

假設有一個dict:{'csev': 2, 'zqian': 1, 'cwen': 4}


[python] view plain copy

temp = list()  

#for k,v in dict.items():  

    temp. is a tuple   

temp.sort(reverse = True )  

print temp  

這樣就可以達到找到最大頻率的目的(統計出現頻率最高的數數)

tuples不僅僅可以包含constant,如下代碼:

a = 1  

b = 99.0  

c = 'hello'  

 

tuple0 = (a, b, c, 1)  

print tuple0  

#tuples 也可包含變量,且變數且constant 的組合,其中tuple0本身也就是一個變數。

列表

List are mutable,所有可以對序列做的同樣適用於列表。

給予一個list 給後續操作:

[python] view plain copy

list0 = [1, 2, 'joe', 99.0]  

# #1. 清單與字串互相轉換:

[python] view plain copy

lst = list('hello')  

#print lst, ''.join( lst)  

2. 改變清單-需要指定清單下標

元素賦值:

[python] view plain copy

list0 = [1, 2, 'joe', 99.0]  

list0[1] = 3  

print list0  ##" range  

刪除特定位置元素:

list0 = [1, 2, 'joe', 99.0]  

del list0[1]  

print list

##del list0[1]  

#0

選擇性賦值-分片



##change value  

name = list( 'Perl')  

name[2:] = list('ar')  

print name  

# change list length and value 

 change list length and value 

 change list length and value 1:] = list('ython')  

print name  

# insert  

numbers = [1,5]  

##numbers = [1,5]  

numbers[1111:11 ] = [2,3,4]  

numbers[0:0] = [0]  

print numbers  

# delete  

##numbers[11 :5] = []  


print numbers  

分片的替換的值必須為清單



##################################################### 3. 結束時追加新物件(一個元素,注意後面的extend)append()######list0 = [1, 2, 'joe', 99.0]  #######list0.append([1, 2])  ######print list0  #############

以上是python序列基礎--元組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn