Python学习笔记3---数据结构

Success in life is a matter not so much of talent and opportunity as of concentration and perseverance.------C. W. Wendtepython

To us.数据结构

 

本文是学习Python 的笔记,只是记下来我认为重要的,易忘的notes,基于A byte of Python中文版Let it be!译。
-----------------------------------------app

1. dir函数函数

内建的dir函数能够列出模块定义的标识符,标识符有函数、类、变量。学习

dir(module)返回模块定义的名称列表,dir()返回当前模块的名称列表。ui

包是模块的文件夹,仅仅是为了方便层次化地组织模块。code

2. 列表listorm

Python中有四种内建的数据结构,列表、元组、字典、集合。对象

list是处理一组有序项目的数据结构,每一个项目用逗号隔开,放在方括号中,list是可变的。排序

shoplist = ['pea', 'watermelon']
shoplist.append('apple')# 添加元素
del shoplist[0]# 删除第一个元素
shoplist.sort()# 按首字母排序元素

3. 元组tuple

元组是不可变的,用()表示。空的元组用myempty=()表示,含有单个元素的元组用singleton=(2,)表示,后跟一个逗号。

tuple = ('apple', 'pea')

4. 字典dict

字典是键值对的组合,键与值之间用冒号分隔,各个对用逗号分隔,用花括号{}表示

# dict

ab = {'liu': 'chongqing', 'zhu': 'heilongjiang', 'hong': 'anhui'}
print("liu's hometown is", ab['liu'])
del ab['hong']  # delete
for name, hometown in ab.items():
    print('contact {0} at {1}' .format(name, hometown))
# use
ab['zhou'] = 'hubei'  # add

列表、元组、字符串都是序列。

5. 切片

shoplist[-1]表示序列最后一个元素,shoplist[:]返回整个序列,shoplist[1:3]不包括第三个元素,shoplist[::2]第三个数为步长,shoplist[::-1]为倒叙返回。

6. 集合set

集合是没有顺序的简单对象的汇集,当在汇集中一个的对象的存在比起顺序或者出现的次数重要时使用集合

bri = set(['china', 'england'])
bri.add('africa')
bri.remove('england')