您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

python序列基础--元组

2024/5/6 22:07:39发布31次查看
元组,跟列表一样,属于序列的一员,不同的是它是不可变序列 
元组的声明:
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
以上就是python序列基础--元组的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product