python序列基础--元组


本文摘自php中文网,作者巴扎黑,侵删。

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

元组的声明:

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序列基础--元组的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python如何创建txt文件并写入

Python和java先学哪个

Python验证码识别教程之灰度处理、二值化、降噪与tesserocr识别

盘点由Python开发的网站和应用

Python如何截取字符串中特定部分

Python人工智能是什么意思

Python文件操作之合并文本文件内容方法介绍

Python强大之处在哪里

Python有for循环吗

Python如何求1到100的奇数和

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...