相信数据结构这个东西,所有学过编程的人都不会陌生。这里只介绍一下Python内置的3种数据结构:列表、元组、字典。
列表(list)
list是用于处理一组有序对象的数据结构。
myList = ['a', 'b', 'c', 'd'];
for element in myList :
print element;
Python中为list提供了一个方法append,可以往列表中添加对象。
myList.append('e');
注意,从list中删除一个对象不是通过list中的方法来实现的。你必须使用del语句来从数组中删除对象。
del myList[2];
你可以运行下面的程序来观察上面提到的情况:
myList = ['a', 'b', 'c', 'd'];
for element in myList :
print element;
print('------------------------');
myList.append('e');
for element in myList :
print element;
print('------------------------');
del myList[2];
for element in myList :
print element;
元组
元组和列表是非常类似的。它们的不同点是元组不可修改。你无法向元组中添加对象,也无法从元组中删除对象。
元组的声明也和列表有所不同,列表使用方括号声明,而元组则使用圆括号来声明。
myTuple = ('a', 'b', 'c', 'd');
for element in myTuple :
print element;
字典
字典就像是通过人名来查询人的联系信息的通讯录。如果你学过Java,那么你一定知道Map,是的,Python中的字典和Java中的Map的功能是非常相似的。
myDict = {'Tom':u'美国','ZhangQiang':u'中国'};
print myDict['ZhangQiang'];
序列
列表、元组、字符串都是序列,但什么是序列吗?序列的2个主要特点索引操作符和切片操作符。这里仅仅举一个例子来说明序列是什么。
shoplist = ['apple', 'mango', 'carrot', 'banana']
# Indexing or 'Subscription' operation
print 'Item 0 is', shoplist[0]
print 'Item 1 is', shoplist[1]
print 'Item 2 is', shoplist[2]
print 'Item 3 is', shoplist[3]
print 'Item -1 is', shoplist[-1]
print 'Item -2 is', shoplist[-2]
# Slicing on a list
print 'Item 1 to 3 is', shoplist[1:3]
print 'Item 2 to end is', shoplist[2:]
print 'Item 1 to -1 is', shoplist[1:-1]
print 'Item start to end is', shoplist[:]
# Slicing on a string
name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]