Rumah  >  Artikel  >  pembangunan bahagian belakang  >  python序列基础--元组

python序列基础--元组

巴扎黑
巴扎黑asal
2017-07-18 13:54:361425semak imbas

元组,跟列表一样,属于序列的一员,不同的是它是不可变序列 

元组的声明:

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.append( (v,k) ) # notice there 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  

list0[99] = 'error' # index out of range  

删除特定位置元素:

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

del list0[1]  

print list0  

选择性赋值——分片



#change value  

name = list('Perl')  

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

print name  

# change list length and value  

name[1:] = list('ython')  

print name  

# insert  

numbers = [1,5]  

numbers[1:1] = [2,3,4]  

numbers[0:0] = [0]  

print numbers  

# delete  

numbers[1:5] = []  

print numbers  

分片的替换的值必须是列表


3. 末尾追加新对象(一个元素,注意后面的extend)append()

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

list0.append([1,2])  

print list0  


Atas ialah kandungan terperinci python序列基础--元组. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:set()类的使用介绍Artikel seterusnya:urllib.request库的使用基础