1.在python中,是最基本的数据结构是序列(sequence).
序列中的每个元素被分配一个序号----即元素的位置,也称为索引(第一个索引从0开始,依次类推)
2.序列
列表和元组区别在于,列表可以修改,元组不可修改。
test = ['test hello',36]
print test[0]
print test[1]
print test
test = ['test hello',40]
value = ['value hello',30]
new = [test, value]
print new
备注:容器数据结构,容器基本包含其的对象的任意对象。序列和映射是两类容器。
序列中的每个元素都有自己的编号,而映射有一个名字(称为键)
2.1.通用序列操作。
所有的序列都可以进行某种特定的操作,比如索引(index),分片(slicing),加(adding),乘(multplying)
以及检查某个元素的序列的成员。除此之外还可以计算序列的长度,找出最大元素和最小元素的内键函数
2.1.1索引(index)
test = 'hello'
print test[0]
负数索引(从右边开始查询)
print test[-1]
直接对返回结果进行索引操作:
test = raw_input("Year: ")[3]
print test
索引示列:
months = [
'January',
'Febuary',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'Decmber'
]
endings = ['st','nd','rd'] + 17 * ['th']\
+['st','nd','rd'] + 7 * ['th']\
+['st']
year = raw_input("Year: ") 1974
month = raw_input("Month (1-12): ") 8
day = raw_input('Day(1-31): ') 16
month_name = months[month_number -1]
ordinal = day + endings[day_number -1]
print month_name +' '+ ordinal + ' '+ year
2.1.2.分片
与使用索引来访问单个元素类似,可以使用分片来访问一定范围内的元素。
分片能过冒号隔开的两个索引来实现
test = 'http://www.perl.org'
print test[11:15]
print test[11:-4]
test = [1,2,3,4,5,6,7,8,9,10]
print test[3:6]
print test[-3:-1]
按步长分片
test=[1,2,3,4,5,6,7,8,9,10]
print test[0:10:1]
print test[1:10:2]
print test[1:10:4]
从右边按步长分处
print test[8:3:-1]
2.1.3.序列相加
[1,2,3] + [4,5,6]
'hello' + 'world'
2.1.4.乘法(重复次数)
'perl' * 5
[6] * 5
空列表可以用[]表示
None是一个python内键值,表示这里什么都没有
2.1.5.检测成员(布尔值)
test = 'hello'
'h' in test
'w' in test
test = ['laomeng','wang','lisi']
raw_input('Enter your name: ') in test
2.1.6.计算长度,最小值和最大值
len(),
min(),
max()
test=[1,2,3,4,5,6,7]
len(test)
minx(test)
max(test)
3.列表
列表是可以变化的--可以改变列表的内容,并且列表有很多有用的,专门的方法
3.1.1.list()函数
list()函数适用于所有类型的序列,而不只是字符串
创建列表
list('hello')
['h','e','l','l','o']
3.1.2.删除元素
test =['abc','abd','abe','abf']
del test[2]
3.1.3.分片赋值
test = list('Perl')
test[2:] = list('ar')
test=[1,5]
test[1:1] =[2,3,4]
删除元素
test =[1,2,3,4,5]
test[1:4]=[]
3.2.列表方法
test =[1,2,3]
3.2.1.append方法用于在末尾增加新的元素
test = [1,2,3,4]
append.test[5]
在perl脚本有同样的功能
my @test = qw(1 2 3 4);
push @test,5;
print "@test\n";
3.2.2.count统计某个元素在列表出现的次数
test = ['a','b','a','b','a','d']
test.count('a')
3.2.3.extend方法可以在序列末尾追加多个值
test = [1,2,3,4,5]
b=[5,7,8]
test.extend(b)
3.3.4.index方法用于从列表中找出某个值的位置
test =['abc','abd','abe','abf','abg']
test.index('abe')
3.3.5.insert方法用于将对象插入列表中
test = [1,2,3,4,5]
test.insert(3,'hello')
3.3.6.pop方法移除列表中的一个元素,默认是最后一个元素,pop是有返回值
test = [1,2,3,4,5]
test.pop()
test.append(pop())
3.3.7.remove方法用于移除列表中某个匹配的值
test =['a','b','c','d']
test.remove('a')
3.3.8.reverse结果取反存放
x=[1,2,3,4]
x.reverse()
x = 'hello'
x.list(reverse())
3.3.9.sort方法是进行排序
x=[4,6,2,1,7,9];
x.sort()
y =x[:]
y.sort()
4.元组: 不可改变序列
1,2,3
()
4.1.1.tulpe函数功能与list函数功能基本上一样
tulpe([1,2,3])
4.1.2元组的基本操作
x = 1,2,3
x[1]
x[0:2]
总结:
序列:是一种数据结构,它包含了元素都行了编号(从0开始).
序列包括了列表,字符串,元组。其中列表可以改变修改的
而元组是不可以修改的。通过分片捷捷操作符可以访问序列的一部分(范围),其中分片需要两个索引来
指出分片的起始和结束位置。
序列成员检测。in操作符可以检查一个值是否存在于序列中。