Python学习Day5
Python的内置函数
|
abs(x) |
求绝对值 |
|
complex([real[, imag]]) |
创建一个复数 |
|
divmod(a, b) |
分别取商和余数 |
|
float([x]) |
将一个字符串或数转换为浮点数。如果无参数将返回0.0 |
|
int([x[, base]]) |
将一个字符转换为int类型,base表示进制 |
|
long([x[, base]]) |
将一个字符转换为long类型 |
|
pow(x, y[, z]) |
返回x的y次幂 |
|
range([start], stop[, step]) |
产生一个序列,默认从0开始 |
|
round(x[, n]) |
四舍五入 |
|
sum(iterable[, start]) |
对集合求和 |
|
oct(x) |
将一个数字转化为8进制 |
|
hex(x) |
将整数x转换为16进制字符串 |
|
chr(i) |
返回整数i对应的ASCII字符 |
|
bin(x) |
将整数x转换为二进制字符串 |
|
bool([x]) |
将x转换为Boolean类型 |
#abs()
x = -123
y = 89
print(abs(x))
print(abs(y))
#all(),循环参数,如果集合中每个元素都为真,则all的返回值为True
b = [11,22,33,44]
a = all(b)
print(a)
#那些元素为假呢?
b = [11,22,33,0]#0,"",[],(),{}, ==》 0,None,空值
a = all(b)
print(a)
#any有一个为真则为真
b = [11,0]
a = any(b)
print(a)



二、集合类操作
|
basestring() |
str和unicode的超类 |
|
format(value [, format_spec]) |
格式化输出字符串 |
|
unichr(i) |
返回给定int类型的unicode |
|
enumerate(sequence [, start = 0]) |
返回一个可枚举的对象,该对象的next()方法将返回一个tuple |
|
iter(o[, sentinel]) |
生成一个对象的迭代器,第二个参数表示分隔符 |
|
max(iterable[, args...][key]) |
返回集合中的最大值 |
|
min(iterable[, args...][key]) |
返回集合中的最小值 |
|
dict([arg]) |
创建数据字典 |
|
list([iterable]) |
将一个集合类转换为另外一个集合类 |
|
set() |
set对象实例化 |
|
frozenset([iterable]) |
产生一个不可变的set |
|
str([object]) |
转换为string类型 |
|
sorted(iterable[, cmp[, key[, reverse]]]) |
队集合排序 |
|
tuple([iterable]) |
生成一个tuple类型 |
|
xrange([start], stop[, step]) |
xrange()函数与range()类似,但xrnage()并不创建列表,而是返回一个xrange对象,它的行为与列表相似,但是只在需要时才计算列表值,当列表很大时,这个特性能为我们节省内存 |
1 a = isinstance("Hello World",str)
2 print(a)
3 # b = isinstance("Hello World",basestring) #在python3中已经放弃了该函数
4 # print(b)
5
6 x = chr(97)
7 print(x)
8 y = chr(98)
9 print(y)
10 z = ord('a')
11 print(z)
12 m = ord('b')
13 print(m) #chr返回整数i对应的ASCII字符。与ord()作用相反。二者结合起来可以对字符串进行相关运算的转换
14 #比如一个字符串str1,转化成另一个字符串str2, 使得 str2[i] = str1[i] - i
15 str1 = "eb:3ej8h"
16 for i in range(0,len(str1)):
17 print(chr(ord(str1[i])-1))

1 for season in ('Spring', 'Summer', 'Fall', 'Winter'):
2 print(season)
3 for season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
4 print(season,type(season))
5 for i,j in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
6 print(i,j)
7 print(type(i)),print(type(j))
8 for i,j in enumerate('abc'):
9 print (i,j)

x = set('spam')
y = set(['h','a','m'])
s = x & y #交集
s1 = x | y #并集
s2 = x - y #差集
print(s,s1,s2)
#快速去除列表中的重复元素
a = [11,22,33,44,11,22]
b = set(a)
c = [i for i in b]
print(c)
s = set([3,5,9,10])
t = set(["hello"])
t.add('x')
s.update([10,37,42])
print(t,s)
print(t)
p = t.remove('hello')
print(p)
t.add('Hello ,World')
print(t)
y = len(t)
print(y)
i = 18 in s
print(i)
u = s.issubset(t)#检测s中的每一元素都在t中
print(u)
o = s.issuperset(t)#检测t中是否每一个元素都在s中
print(o)


s.union(t) s | t 返回一个新的 set 包含 s 和 t 中的每一个元素 s.intersection(t) s & t 返回一个新的 set 包含 s 和 t 中的公共元素 s.difference(t) s - t 返回一个新的 set 包含 s 中有但是 t 中没有的元素 s.symmetric_difference(t) s ^ t 返回一个新的 set 包含 s 和 t 中不重复的元素 s.copy() 返回 set “s”的一个浅复制

三、逻辑判断
|
all(iterable) |
1、集合中的元素都为真的时候为真 |
|
any(iterable) |
1、集合中的元素有一个为真的时候为真 |
|
cmp(x, y) |
如果x < y ,返回负数;x == y, 返回0;x > y,返回正数 |
#all(),循环参数,如果集合中每个元素都为真,则all的返回值为True
b = [11,22,33,44]
a = all(b)
print(a)
#那些元素为假呢?
b = [11,22,33,0]#0,"",[],(),{}, ==》 0,None,空值
a = all(b)
print(a)
#any有一个为真则为真
b = [11,0]
a = any(b)
print(a)
四、反射
|
callable(object) |
检查对象object是否可调用 |
|
classmethod() |
1、注解,用来说明这个方式是个类方法 |
|
compile(source, filename, mode[, flags[, dont_inherit]]) |
将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。 |
|
dir([object]) |
1、不带参数时,返回当前范围内的变量、方法和定义的类型列表; |
|
delattr(object, name) |
删除object对象名为name的属性 |
|
eval(expression [, globals [, locals]]) |
计算表达式expression的值 |
|
execfile(filename [, globals [, locals]]) |
用法类似exec(),不同的是execfile的参数filename为文件名,而exec的参数为字符串。 |
|
filter(function, iterable) |
构造一个序列,等价于[ item for item in iterable if function(item)] |
|
getattr(object, name [, defalut]) |
获取一个类的属性 |
|
globals() |
返回一个描述当前全局符号表的字典 |
|
hasattr(object, name) |
判断对象object是否包含名为name的特性 |
|
hash(object) |
如果对象object为哈希表类型,返回对象object的哈希值 |
|
id(object) |
返回对象的唯一标识 |
|
isinstance(object, classinfo) |
判断object是否是class的实例 |
|
issubclass(class, classinfo) |
判断是否是子类 |
|
len(s) |
返回集合长度 |
|
locals() |
返回当前的变量列表 |
|
map(function, iterable, ...) |
遍历每个元素,执行function操作 |
|
memoryview(obj) |
返回一个内存镜像类型的对象 |
|
next(iterator[, default]) |
类似于iterator.next() |
|
object() |
基类 |
|
property([fget[, fset[, fdel[, doc]]]]) |
属性访问的包装类,设置后可以通过c.x=value等来访问setter和getter |
|
reduce(function, iterable[, initializer]) |
合并操作,从第一个开始是前两个参数,然后是前两个的结果与第三个合并进行处理,以此类推 |
|
reload(module) |
重新加载模块 |
|
setattr(object, name, value) |
设置属性值 |
|
repr(object) |
将一个对象变幻为可打印的格式 |
|
slice() |
|
|
staticmethod |
声明静态方法,是个注解 |
|
super(type[, object-or-type]) |
引用父类 |
|
type(object) |
返回该object的类型 |
|
vars([object]) |
返回对象的变量,若无参数与dict()方法类似 |
|
bytearray([source [, encoding [, errors]]]) |
返回一个byte数组 |
|
zip([iterable, ...]) |
实在是没有看懂,只是看到了矩阵的变幻方面 |
五、IO操作
|
file(filename [, mode [, bufsize]]) |
file类型的构造函数,作用为打开一个文件,如果文件不存在且mode为写或追加时,文件将被创建。添加‘b’到mode参数中,将对文件以二进制形式操作。添加‘+’到mode参数中,将允许对文件同时进行读写操作 |
|
input([prompt]) |
获取用户输入 |
|
open(name[, mode[, buffering]]) |
打开文件 |
|
|
打印函数 |
|
raw_input([prompt]) |
设置输入,输入都是作为字符串处理 |
open函数,该函数用于文件处理
操作文件时,一般需要经历如下步骤:
- 打开文件
- 操作文件
file object = open(file_name [, access_mode][, buffering])
'''各个参数的细节如下:
file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。
access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。
buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。
'''
一、打开文件
|
1
|
文件句柄 = open('文件路径', '模式') |
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r ,只读模式【默认】
- w,只写模式【不可读;不存在则创建;存在则清空内容;】
- x, 只写模式【不可读;不存在则创建,存在则报错】
- a, 追加模式【可读; 不存在则创建;存在则只追加内容;】
write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
write()方法不会在字符串的结尾添加换行符('\n'):
"+" 表示可以同时读写某个文件
- r+, 读写【可读,可写】
- w+,写读【可读,可写】
- x+ ,写读【可读,可写】
- a+, 写读【可读,可写】
"b"表示以字节的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型
#!/usr/bin/env python3
#_*_coding:utf-8_*_
f = open("ha.log","w",encoding="utf-8")
print("文件名",f.name)
print("是否关闭",f.closed)
print("访问模式",f.mode)
f.close() #关闭打开的文件
f1 = open("ha1.log","w",encoding="utf-8")
f1.write("laonanhai\n Very good site!\n")
f1.close()
f2 = open("ha1.log","r",encoding="utf-8")
str = f2.read()
str1 = f2.read(10)
print(str,str1)
position = f2.tell()
print("当前文件位置",position)
position1 = f2.seek(0,0)
str3 = f2.seek(10)
print("重新读取字符串",str3)
f2.close()

3.x操作
class TextIOWrapper(_TextIOBase): """ Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see help(codecs.Codec) or the documentation for codecs.register) and defaults to "strict". newline controls how line endings are handled. It can be None, '', '\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. If line_buffering is True, a call to flush is implied when a call to write contains a newline character. """ def close(self, *args, **kwargs): # real signature unknown 关闭文件 pass def fileno(self, *args, **kwargs): # real signature unknown 文件描述符 pass def flush(self, *args, **kwargs): # real signature unknown 刷新文件内部缓冲区 pass def isatty(self, *args, **kwargs): # real signature unknown 判断文件是否是同意tty设备 pass def read(self, *args, **kwargs): # real signature unknown 读取指定字节数据 pass def readable(self, *args, **kwargs): # real signature unknown 是否可读 pass def readline(self, *args, **kwargs): # real signature unknown 仅读取一行数据 pass def seek(self, *args, **kwargs): # real signature unknown 指定文件中指针位置 pass def seekable(self, *args, **kwargs): # real signature unknown 指针是否可操作 pass def tell(self, *args, **kwargs): # real signature unknown 获取指针位置 pass def truncate(self, *args, **kwargs): # real signature unknown 截断数据,仅保留指定之前数据 pass def writable(self, *args, **kwargs): # real signature unknown 是否可写 pass def write(self, *args, **kwargs): # real signature unknown 写内容 pass def __getstate__(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __next__(self, *args, **kwargs): # real signature unknown """ Implement next(self). """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 3.x

浙公网安备 33010602011771号