python--序列的基本概念和操作(序列:列表、元组、字符串)
序列:python中最基本的数据结构,每一个元素被分配一个需要——元素的位置,亦称“索引”,首个索引为0,第二个为1,后面依此类推。python包含六种内建的序列类型:列表、元组、字符串、Unicode字符串、buffer对象和xrange对象。
列表、元组和字符串是典型的序列类型,其中,列表可变(可以进行修改),元组和字符串不可变(一旦创建了就是固定的)。
字符串:’I love you,baby!’等,列表:[1,2,3,5,4]等,元组:(1,2,3,4,5)等
python还有一种名为容器(container)的数据结构,容器可以包含其他任意对象,容器主要包括序列和映射(例如:字典)两类。序列的每个元素都有自己的编号,而映射每个元素则有一个叫做“键”的名字。集合是另一种容器。
一、序列的通用操作(IDLE中的演示)
1、索引:
>>>greeting = ‘hello’
>>>greeting[1]
‘e’
>>>greeting[-1]
‘o’
>>>fourth = raw_input(‘Year: ‘)[3]
Year: 2013
>>>fourth
’3′
2、分片
>>>nums = [1,2,3,4,5,6,7,8,9,0]
>>>nums[3:6]
[4,5,6]
>>>nums[0:1]
[1]
>>>nums[7:10]
[8,9,0]
>>>nums[-3:-1]
[8,9]
>>>nums[-3:]
[8,9,0]
>>>nums[-3:0]
[]
>>>nums[:3]
[1,2,3]
>>>nums[:]
[1,2,3,4,5,6,7,8,9,0]
>>>nums[0:10:2]#2代表步长(不能为0),0是起始位置(包括本身),10是终点(不包括其本身)
[1,3,5,7,9]
>>>nums[3:6:3]
[4]
>>>nums[::4]
[1,5,9]
>>>nums[8:3:-1]
[9,8,7,6,5]
>>>nums[10:0:-2]
[0,8,6,4,2]
>>>nums[0:10:-2]
[]
>>>nums[::-2]
[0,8,6,4,2]
>>>nums[5::-2]
[6,4,2]
>>>nums[:5:-2]
[10,8]
3、序列相加
>>>[1,2,3] + [4,5,6]
[1,2,3,4,5,6]
>>>’hello ‘ + ‘world!’
‘hello world!’
不同类型的序列不能直接用’+'连接相加,如不能直接:列表+字符串
4、乘法
>>>’python’ * 5
>>> ‘pythonpythonpythonpythonpython’
>>>[42] * 10
[42,42,42,42,42,42,42,42,42,42]
#空列表及其初始化、None
#None为python内建值表示“这里什么也没有”,则列表可使用如下语句初始化:
>>>seq = [None] * 10
>>>seq
[None, None, None, None, None, None, None, None, None, None]
5、成员资格检查
>>>permissions = ‘rw’
>>>’w’ in permissions
True
>>>’x’ in permissions
False
>>>users = ['mlh','foo','root']
>>>raw_input(‘Enter your user name: ‘) in users
Enter your user name: root
True
>>>s = ‘i dont so serious!’
>>>’so’ in s
True
#如下设计简单的权限管理系统(保存在单独的accessGranted.py中)
database = [['qlp','1234'],['qlp2','2345'],['qlp3','3456'],['qlp4','2134']]
while 1:
username = raw_input(‘User name: ‘)
pin = raw_input(‘Pin code: ‘)
if [username,pin] in database:
print ‘Access Granted’
else: print ‘Username or Pin code is wrong, continue(Y) or quit(other)?’
press = raw_input()
if press!=’Y’ and press!=’y':
print ‘Enter is not Y’ break #else: #print ‘Enter is Y’
6、长度、最小值、最大值
>>>nums = [23,14,78]
>>>len(nums)
3
>>>max(nums)
78
>>>min(nums)
14
>>>max(2,3)
3
>>>min(5,4,6,3,85,4)
3