【编程语言学习——python】02列表和元组

序列是python中最基本的数据结构,类型包括列表、元组、字符串、Unicode字符串、buffer对象和xrange对象。
列表与元组最主要的区别是:列表可以修改,元组不能

通用序列操作

1.索引

所有元素可以通过编号(从0开始递增)分别访问。

小示例:给定年月日打印日期

ending=['st','nd','rd']+17*['th']+['st','nd','rd']+7*['th']+['st']
#创建第1-31天的后缀列表
months=['January','February','March','April','May',
'June','July','August','September','October','November','December']
#输入年月日
year=raw_input('Year:')
month=raw_input('Month(1-12):')
day=raw_input('Day(1-31):')
#转化成整型,才能进行后续加减操作
month_n=int(month)
day_n=int(day)
#减1获得正确索引
month_m=months[month_n-1]
ordinal=ending[day_n-1]
print month_m+' '+day+ordinal+','+year

tips
input()默认输入的是合法表达式
raw_input()会将输入的东西变成字符串

2.分片

访问一定范围内的元素
规则:算头不算尾
捷径:空最后一个索引可以得到序列结尾所有元素。空两个索引可以复制整个序列。
步长:可以按照步长间隔遍历序列的元素。

>>>x=[1,2,3,4]
>>> x[1:3]
[2, 3]
>>> x[1:]
[2, 3, 4]
>>> x[1:-1]
[2, 3]
>>> x[:]
[1, 2, 3, 4]
>>> x[0:2:2]
[1]
>>> x[0:3:2]
[1, 3]

3.相加、相乘、成员资格

>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> [1,2,3]*2
[1, 2, 3, 1, 2, 3]
>>> [None]*3
[None, None, None]
>>> 'w' in 'wang'
True

4.长度、最小最大值函数

>>> x=[1,2,3,4]
>>> len(x)
4
>>> min(x)
1
>>> max(x)
4

基本列表操作

包括赋值、删除元组、分片替换删除等。

>>> x=[1,2,3,4,5,6,7]
>>> x[1]=3##列表赋值
>>> x
[1, 3, 3, 4, 5, 6, 7]
>>> del x[1]##删除元素
>>> x
[1, 3, 4, 5, 6, 7]
>>> x[1:3]=[8,9,10]
>>> x
[1, 8, 9, 10, 5, 6, 7]
>>> x[1:4]=[]##分片删除
>>> x
[1, 5, 6, 7]

字符串变列表的函数:list

>>> list('python')
['p', 'y', 't', 'h', 'o', 'n']

列表方法

调用方式: 对象.方法(参数)

方法 含义 备注
append 在列表末尾追加新对象 不返回值,直接修改列表
extend 在列表末尾追加多个值 不返回值,直接修改列表
insert 将对象插入到列表中 不返回值,直接修改列表
remove 移除列表中某个值的第一个匹配项 不返回值,直接修改列表
reverse 将列表中元素反向存放 不返回值,直接修改列表
sort 对列表排序 不返回值,直接修改列表
count 统计某个元素在列表中出现的次数 返回值
index 从列表中找出某个值第一个匹配项的位置 返回值
pop 移除列表中最后一个元素 返回该元素的值并修改列表
>>> x=[1,2,3,4,5,6]
>>> x.append(0)
>>> x
[1, 2, 3, 4, 5, 6, 0]
>>> x.count(1)
1
>>> y=[8,9]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6, 0, 8, 9]
>>> x.index(3)
2
>>> x.insert(1,'three')
>>> x
[1, 'three', 2, 3, 4, 5, 6, 0, 8, 9]
>>> x.pop()
9
>>> x.remove(1)
>>> x
['three', 2, 3, 4, 5, 6, 0, 8]
>>> x.reverse()
>>> x
[8, 0, 6, 5, 4, 3, 2, 'three']
>>> x.sort()
>>> x
[0, 2, 3, 4, 5, 6, 8, 'three']

元组

>>> 1,2,3
(1, 2, 3)
>>> 2,
(2,)
>>> tuple('abc')
('a', 'b', 'c')
>>> x=1,2,3
>>> x[2]
3

阅读、练习加总结总用时2.5h
下次争取提高效率!
加油鸭!

猜你喜欢

转载自blog.csdn.net/xiangshiyi0724/article/details/84724159
今日推荐