6.数据结构

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangyang20170901/article/details/84931400

时间: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

扫描二维码关注公众号,回复: 4747184 查看本文章

3.字典

  键值keys与value联系在一起,键值是唯一的。

 只能使用不可变的对象(如字符串)作为字典的键值,值可变不可变都可以。

 字典中的键值-值不会以任何方式进行排序,只能在使用之前定义一个顺序。

ab = {
    'Swaroop':'[email protected]',
    'Larry':'[email protected]',
    'Matsumoto':'[email protected]',
    'Spammer':'[email protected]'
}#创建一个字典
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']='[email protected]'#添加一个项目

if 'Guido' in ab:#用in检测某对键值是否存在
    print("\nGuido's address is",ab['Guido'])

4.序列

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

猜你喜欢

转载自blog.csdn.net/wangyang20170901/article/details/84931400