大蟒日志9

十二、Data Structures(数据结构) 1

综述

Python中的数据结构包含四种:list, tuple, dictionary, set, 即列表、元组、字典、集合。

List

列表:保存一系列有序项目的集合。示例如下:

# 2018.4.23
# Data Structures
# List
# Shopping list
# 要购物清单内容,有几项
shoplist = ['vegetables', 'fruits', 'fly', 'Wine', '1L Beer']
print('I have', len(shoplist), 'items to purchase.')

# 打印购物清单
print('These items are:', end=' ')
for item in shoplist:
    print(item, end=' ')
# 这里的end=' '使得列表显示为空格隔开每一项,如果没有end则按行显示每一项

# 用append方法对shoplist这一对象中加入milk,并打印加入后的购物单
print('\nAlso have to buy milk.')
shoplist.append('2L milk')
print('Shopping list is now', shoplist)

# 整理购物清单,用sort method进行排序
print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)

# 已购买第一项,从列表中删除此项,并打印删除后的购物单
print('First item is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I have bought the', olditem)
print('Shopping list is now', shoplist)

# 编译结果为:(注意其中的排列规则)
'''
I have 5 items to purchase.
These items are: vegetables fruits fly Wine 1L Beer 
Also have to buy milk.
Shopping list is now ['vegetables', 'fruits', 'fly', 'Wine', '1L Beer', '2L milk']
I will sort my list now
Sorted shopping list is ['1L Beer', '2L milk', 'Wine', 'fly', 'fruits', 'vegetables']
First item is 1L Beer
I have bought the 1L Beer
Shopping list is now ['2L milk', 'Wine', 'fly', 'fruits', 'vegetables']
'''
#补充: 如果想了解其他的关于对象“list”的方法,可以用help(list)来了解。

附加:对象(Object)与类(Class)的简单了解
列表是使用对象与类的一个实例。
一个类可以带有方法(Method)或字段(Field)。对于method来说,当你有一个属于该类的对象时,你才能用method来启用某些函数;对于field来说,它只为该类定义和使用变量,同样当你有一个属于该类的对象时,你才能用field中的变量或名称。
method和field都可以用点号来访问对象,比如:shoplist.append(‘2L milk’),shoplist.field

Tuple

元组用于将多个对象保存在一起。括号括住,逗号隔开。

# 2018.4.26
# Tuple
# 可以结合C语言中的数组来理解
# 强烈建议使用tuple时用括号括起来。
# Explicit is better than implicit.
# 明了胜于隐晦,显式优于隐式

# Ex.动物园动物搬家
zoo = ('python','elephant','penguin')  # 元组中有3个元素
print('Number of cages 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, end=', ')
print(new_zoo[0],'are brought from old zoo') # [ ] 称为索引运算符,new_zoo[2]指定元组的第三个项目
print('First one brought from old zoo is', new_zoo[2][0], end=', ') # [2][0] 第三组第一项
print('then', new_zoo[2][1], end=', ') # new_zoo[a][b]指定元组的第a个项目中的第b个项目
print('last', new_zoo[2][2])
print('Number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2]))


# 补充: 
# 空元组
myempty = ()
# 只有一个项目的元组
single = (2, )
print(single[0])
'''
编译结果为:
Number of cages 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')), monkey are brought from old zoo
First one brought from old zoo is python, then elephant, last penguin
Number of animals in the new zoo is 5
2
'''

【声明】本博文为学习笔记,含有个人修改成分,并非完全依照《a byte of python》,仅供参考。若发现有错误的地方,请不吝赐教,谢谢。同时,我也会不定期回顾,及时纠正。#

猜你喜欢

转载自blog.csdn.net/csdner_0/article/details/80087392