python之list,tuple,str,dic简单记录(二)

切片对象:
例子:
In [13]: l = [1,23,4,5,5,6,8]
In [14]: l[::1]
Out[14]: [1, 23, 4, 5, 5, 6, 8]

In [15]: l[::2]
Out[15]: [1, 4, 5, 8]

In [16]: l[::3]
Out[16]: [1, 5, 8]

In [17]: l[1:4]
Out[17]: [23, 4, 5]

检查类型(isinstance函数的使用)
isinstance()接受一个元组对象为参数
例子:
In [68]: def displayNumType(num):
...: print num,'is',
...: if isinstance(num,(int,long,float,complex,bool,str,list,tuple)):
...: print 'a number of type:',type(num).__name__
...: else:
...: print 'not exists'
...:

In [69]: displayNumType('str')
str is a number of type: str

In [70]: displayNumType([1,23,3,4])
[1, 23, 3, 4] is a number of type: list

In [71]: displayNumType(99)
99 is a number of type: int

In [72]: displayNumType(88.23)
88.23 is a number of type: float

In [73]: displayNumType(True)
True is a number of type: bool

值比较:
<,>,<=,>=,==,!=
对象比较:
is,is not
布尔操作符:
not,and,or

列表,元组,字典都是容器类型
以更新模型为标准的类型分类:
可变类型:列表,字典
不可变类型:数字,字符串,元祖
通过内建函数id()来确认对象身份在两次赋值后是否变化
例子:
In [74]: id(a)
Out[74]: 66969152

In [75]: q = 'xxx'

In [76]: id(q)
Out[76]: 65543608

In [77]: q='xxxxxx'

In [78]: id(q)
Out[78]: 67362240

In [79]: ql = [1,23,4,1,4]

In [80]: id(ql)
Out[80]: 67150032

In [81]: ql.append('name')

In [82]: ql
Out[82]: [1, 23, 4, 1, 4, 'name']

In [83]: id(ql)
Out[83]: 67150032

访问模型:根据访问我们存储的数据的方式对数据类型进行分类
访问模型共有三种方式:直接获取,顺序,和映射
序列类型是指容器内的元素从0开始的索引顺序访问,一次访问一个或者多个,也就是切片(slice)。
映射类型类似序列的索引属性,不过他的索引并不是使用顺序的数字偏移量取值,它的元素无序存放,通过一个唯一的键来访问,它容纳的是哈希键-值得集合。


以访问模型为标准的类型分类:
分类 python类型
直接访问 数字
顺序访问 字符串,列表,元组
映射访问 字典

os.walk方法

os模块提供的walk方法很强大,能够把给定的目录下的所有目录和文件遍历出来。

方法:os.walk(path),遍历path,返回一个对象,他的每个部分都是一个三元组,('目录x',[目录x下的目录list],目录x下面的文件)

import os
def walk_dir(dir,fileinfo,topdown=True):
for root, dirs, files in os.walk(dir, topdown):
for name in files:
print(os.path.join(name))
fileinfo.write(os.path.join(root,name) + ' ')
for name in dirs:
print(os.path.join(name))
fileinfo.write(' ' + os.path.join(root,name) + ' ')
dir = raw_input('please input the path:')
fileinfo = open('list.txt','w')
walk_dir(dir,fileinfo)

原文地址:https://www.cnblogs.com/misswangxing/p/7840751.html