您的位置:首页 > 理论基础 > 数据结构算法

Python笔记(2)——数据类型和数据结构

2016-02-17 21:28 295 查看
本篇了解一下Python的基础数据类型和数据结构。

一 基础数据类型

基础数据类型描述举例
整形(int)包括负整数、
无大小限制
a=1

print(type(a)) #<class 'int'>
浮点型(float)无大小限制
e=.3.2e1 #3.2

print(type(e)) #<class 'float'>
布尔类型(bool)逻辑值
True False

区分大小写
print(type(True)) #<class 'bool'>
bytes一个由字节组成的
不可更改的有串行
bys=b'abc'

print(type(bys)) #<class 'bytes'>

print(bys[0]=='a') #False

print(bys[0]==97) #True
字符串(str)一个由字符组成的
不可更改的有序列。
在Python 3.x里,
由Unicode字符组成。
s1='hello:\n'

s2="I'm xiaoyang"

s3='''hello,

xiaoyang'''

print(type(s3))        #<class 'str'>

print("%s,%s,%s" %(s1,s2,s3))
空值(NoneType)用None表示空值
print(None is None)  #True

print(type(None))  #<class 'NoneType'>

二 数据结构

下面主要介绍Python中简单的数据结构,后续章节专门研究Python的集合库。

2.1 list

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#定义list
l=['python',3,'in','one']
#打印l类型
print(type(l))
#打印l长度
print(len(l))
#获取第一个值
print(l[0])
#获取最后一个值
print(l[-1])
#list尾部添加元素
l.append('pic')
#list指定位置添加元素
l.insert(2,'4')
#list移除指定位置元素
print(l.pop(2))
#返回指定位置索引
print(l.index('3'))


2.2 tuple

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#定义tuple
tp=(1,2,3,[4,5])
print(type(tp))
#打印指定位置元素
print(tp[2])
#定义具有单个元素的tuple,必须加一个逗号;
tp=(1,)


2.3 set

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#声明一个set变量
st={'s','w','t'}
print(type(st))
#打印st长度
print(len(st))
#声明一个空值得set变量
st=set()
print(type(st))
#打印st长度
print(len(st))
st=set(['s','e','t'])
#添加元素
st.add('t')
#移除某个元素
st.remove('T')
#清空集合
st.clear()


2.4 dict(键值对)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#声明一个空dict变量
dic={}
print(type(dic))
#声明一个有值得dict变量
dic={'k1':'v1','k2':'v2'}
#打印dict长度
print(len(dic))
#打印指定key的值
print(dic['k2'])
print(dic.get('k1'))
#指定key重新赋值
dic['k2']='v3'
print(dic)
#判断是否存在指点key
print('k2' in dic)


三 总结

集合类型特征描述与Java类比
list一组可改变的有序集合ArrayList
tuple不可改变的有序集合Array
set没有重复元素的无序集合Hashset
dict存储键值对的集合HashMap

参考文章

1.Python维基百科 https://zh.wikipedia.org/wiki/Python

2.廖雪峰Python教程

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: