Python 数据结构

2018-11-12  本文已影响8人  CaptainRoy

Python 有四种内置的数据结构 - 列表(List),元组(Tuple),字典(Dictionary),集合(Set)

List 列表
shopList = ['apple','mango','carrot','banana']

print('I have',len(shopList),'items to purchase.')

for item in shopList:
    print(item)

shopList.append('rice')

print(shopList) # ['apple', 'mango', 'carrot', 'banana', 'rice']

shopList.sort()
print(shopList) # ['apple', 'banana', 'carrot', 'mango', 'rice']

print(shopList[1])

del shopList[0]
print(shopList) # ['banana', 'carrot', 'mango', 'rice']
元组
zoo = ('python','elephant','penguin') # ('python', 'elephant', 'penguin')
print(len(zoo)) # 3

newZoo = ('monkey','camel',zoo)
print(newZoo) # ('monkey', 'camel', ('python', 'elephant', 'penguin'))

print(newZoo[2]) # ('python', 'elephant', 'penguin')
print(newZoo[2][2]) # penguin
字典
address = {
    'roy' : 'roy@icloud.com',
    'lily' : 'lily@mail.com',
    'leo' : 'leo@hotmail.com'
}

for name,mail in address.items():
    print('name:',name,'email:',mail)

del address['roy']

address['faker'] = 'faker@qq.com'
集合
bri = {'brazil','russia','india'}

result = 'russia' in bri

bri.add('china')

bri.remove('india')
上一篇 下一篇

猜你喜欢

热点阅读