6.数据结构

时间:2018年12月9日20:08:43

---------------------------------------------------------------------------------------

0.四种:列表,元组,字典,集合

1.列表

      可变数据类型(可以添加,移除,删改),用于保存一系列有序项目的集合

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 shopping 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)

输出结果:

I have 4 items to purchase
These items are: apple mango carrot banana 
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the  apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']

2.元组

     将多个对象保存到一起,元组不可改变,不能编辑或更改元组。

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 brought from old zoo are',new_zoo[2])
print('Last animal brought from the lod zoo is',new_zoo[2][2])
print('Number of animals in the new zoo is',
      len(new_zoo)-1+len(new_zoo[2]))

输出结果为:

Number of animals in the zoo is 3
Number of cages in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from the lod zoo is penguin
Number of animals in the new zoo is 5

3.字典

  键值keys与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'])
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:#用in检测某对键值是否存在
    print("\nGuido's address is",ab['Guido'])

4.序列

  列表,元组,字符串都可以看做序列的某种表现形式,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值