您的位置:首页 > 理论基础 > 数据结构算法

简明python教程--数据结构篇

2017-09-22 09:57 393 查看
熟练掌握数据结构,可以让我们的程序简洁、高效,本篇内容主要列举python数据结构实例,方便查找和积累掌握!

python内置的四种数据结构:列表(list),元组(tuple),字典(dictionary),集合(set)

1.列表(list)

列表是一种用于保存一系列有序项目的集合,使用方括号标识[ ]

#This ia my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']

print('I have', len(shoplist), 'items to purchase')
print('These items are:', end=' ')
for item in shoplist:
print(item, end=' ')

print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopplist list is now', shoplist)

print('i will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)

print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist)

2.元组(tuple)

元组用于将多个对象保存到一起,你可以将它们近似地看做列表,但是元组的不可改变,改变元组需要使用切片技术。

元组使用逗号分隔

#我会推荐你总是使用括号来指明元组的开始于结束
#尽管括号是一个可选选项,明了胜过晦涩,显式优于隐式
zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))

new_zoo = 'monkey', 'camel', zoo
print('number of cages in the new zoo is', len(new_zoo))
print('all animals in new zoo are', new_zoo)
print('Animals broght from old zoo are', new_zoo[2])
print('Last animal broght from old zoo is', new_zoo[2][2])
print('number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2]))
3.字典(dict)

字典就像一本地址簿,如果你有姓名,你就可以找到他的地址。

在字典中,你可以使用符号构成d={key:value1, key2:value2},其中key是唯一的,使用不可变的字符串类型,value可以可变或不可变。

ab = {
'swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'spammer': 'spammer@hotmail.com'
}

print('swaroop\'s address is', ab['swaroop'])
print("swaroop's address is", ab['swaroop'])

#删除一对键值对
del ab['spammer']
print('\nThere are {}contacts in the address-book\n'.format(len(ab)))

for name, address in ab.items():
print('Contact {} at {}'.format(name, address))

#添加一对键值对
ab['Guido'] = 'guido@python.org'
if 'Guido' in ab:
print('\nGuido\'s address is', ab['Guido'])

4.序列

列表、元组和字符串都是序列,序列的主要特点是索引操作符和切片操作符。

序列的主要功能是资格测试(in与not in)和索引操作。

索引操作符可以从序列中抓取一个特定项目。

切片操作符能够获取序列的一个切片,即一部分序列。

shoplist = ['apple', 'mango', 'carrot', 'banana']

name = 'swaroop'

#索引或下标操作符

print('Item o 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])

print('character o is', name[0])

#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[:])

#从某一字符串中切片

print('characters 1 to 3 is', name[1:3])

print('character 2 to end is', name[2:])

print('characters 1 to -1 is',name[1:-1])

print('characters start to end is', name[:])

5.集合(set)

集合是简单对象的无序集合,当集合中的项目存在与否比起次序或者出现次数更加重要时,我们就会使用集合。

通过使用集合,你可以测试某些对象的资格或情况,检查他们是否是其他集合的子集,找到两个集合的交集。

>>> bri = set(['brazil', 'russia', 'india'])

>>> print(bri)

{'brazil', 'russia', 'india'}

>>> 'india' in bri

True

>>> 'usa' in bri

False

>>> bric = bri.copy()

>>> bric.add('china')

>>> bric.issuperset(bri)

True

>>> bri.remove('russia')

>>> bri & bric

{'brazil', 'india'}

>>>

6.引用

当你创建一个对象并将其分配给某个变量时,变量会查阅某个对象,但不会代表对象本身。

变量名只是指向计算机内存中存储相应对象的那一部分。

print('Simple assignment')

shoplist = ['apple', 'mango', 'carrot', 'banana']

mylist = shoplist

del shoplist[0]

print('shoplist is', shoplist)

print('mylist is', mylist)

print('copy by makeing a full slice')

mylist = shoplist[:]

del mylist[0]

print('shoplist is', shoplist)

print('mylist is', mylist)

7.字符串

程序中使用的所有字符串都是str类的对象。

#这是一个字符串对象

name = 'Swaroop'

if name.startswith('Swa'):

    print('Yes, the string starts with "Swa"')

if 'a' in name:

    print('Yes, it contains the string "a"')

if name.find('war') != -1:

    print('Yes, it contains the string "war"')

delimiter = '_*_'

mylist = ['Brazil', 'Russia', 'India', 'China']

print(delimiter.join(mylist))


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息