数据结构是通过某种方式(例如对元素进行编号组织在一起的数据元素的集合)。
在Python中,最基本的数据结构是序列。
Python中包含6种内建的序列 (列表,元组,字符串,Unicode字符串,buffer对象和xrange对象)
注意:在Python中,还有一种数据结构叫做容器。容器包含了序列、映射和集合。
1 通用序列操作
1.1 索引
位置索引
1.2 分片/切片
#分片操作:提供两个索引作为边界,第一个索引元素在内,第二个索引不在分片内
numbers=[1,2,3,4,5,6,7,8,9,10]
print(numbers[3:6]) #[4,5,6]
print(numbers[0:1]) #[1]
print(numbers[-3:]) #[8,9,10],提取到最后的元素可以直接用空
print(numbers[:3]) #[1,2,3],提取最开始的元素可以直接用空
print(numbers[:]) #[1,2,3,4,5,6,7,8,9,10]
设置步长
正数:从左到右
负数:从右到左
1.3 序列相加
相同类型的序列可以相加
1.4 乘法
#17*['th']:表示生成17个'th'
endings = ['st','nd', 'rd'] + 17*['th']\
+ ['st','nd', 'rd'] + 7*['th']\
+ ['st']
print(endings)
>>>['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st']
1.5 in运算符
in运算符查看一个值是否在序列中。
实例:
Unix系统中,查看文件可写和可执行权限的脚本;
检查所提供的用户名是否在用户列表中;
垃圾邮件过滤器的一部分/检查字符串中是否含有另外一个字符串。
#序列成员资格实例
database=[
['John','1234'],
['Allen','2345'],
['hannah','3456']
]
username = input('请输入姓名:\n')
pin = input('请输入pin码:\n')
if [username,pin] in database:
print('Access Permitted')
else:
print('Access Denied')
这个知识让我想到了剪刀石头布游戏的解法,有兴趣自己可以去思考一下。
#***************小游戏:剪刀石头布***************
import random
GuessList = [
'剪刀',
'石头',
'布'
]
WinList = [
['剪刀','布'],
['石头','剪刀'],
['布','石头']
]
while True:
try:
Computer_choice = random.choice(GuessList)
My_choice = input('请输入你的招数:\n').strip()
while My_choice not in GuessList:
My_choice = input('请输入你的招数:\n').strip()
continue
if Computer_choice == My_choice:
print('平手')
elif [Computer_choice,My_choice] in WinList:
print('电脑赢')
else:
print('我赢')
finally:
break
1.6 len() max() min()
len(): 返回长度
max(): 返回最大值
min(): 返回最小值
2 列表
2.1 基本的列表操作
del list[2]
list[2] =2
name[1:] = list('python')
2.2 列表方法
方法的调用方法:
对象.方法(参数)
append:在列表末尾追加新的对象。【直接修改原来的列表】lst.append(3)
count:统计某个元素在列表中出现的次数。x.count(1)
extend:在列表的末尾一次性追加另个序列中的多个值,也就是用新列表扩展原有列表【修改了原有列表】。a.extend(b)
index:从列表中找出某个值第一个匹配项的索引位置。numbers.index(2)
insert:将对象插入到列表中。numbers.insert(3,"four")【改变列表】
pop: 移除列表中的一个元素,默认最后一个,并返回该元素的值x.pop()【改变列表】
remove:移除列表中某个值的第一个匹配项。x.remove('be')【改变列表】
reverse: 将列表中的元素反向存放。【改变列表】
sort:在原位置对列表排序【改变原来的列表】。
x = [1,3,6,5,4]
#x[:]得到的是包含了所有元素的分片
y = x[:]
y.sort()
print(y)
print(x)
#无效,x和y指向同一个列表
y = x
y.sort()
print(y)
print(x)
x = [1,3,6,5,4]
#sorted()不改变原来的x
y = sorted(x)