琪齐

空想终日彷徨行动方可无惧!

导航

lambda表达式、内置函数、进制和文件操作

Posted on 2016-05-10 17:55  琪齐  阅读(995)  评论(0编辑  收藏  举报

lambda表达式

定义函数(普通方式)
def
f1(): return 123 f2 = lambda : 123 def f3(a1,a2): return a1+a2 定义函数(lambda表达式)
f4
= lambda a1,a2: a1+a2

示例:
def f1(x):
if x % 2 ==1:
return x + 100
else:
return x

ret = map(lambda x: x + 100 if x % 2 ==1 else x, [1,2,3,4])
# print(ret)
for i in ret:
print(i)
运算结果:

101
2
103
4

 内置函数

 1,abs()  

绝对值

参数可以是:负数、正数、浮点数或者长整形

i = abs(-123) #绝对值
print(i)

i = abs(-1.2)
print(i)

i = abs(1.2) 
print(i)

i = abs(-11216.5) 
print(i)

i = abs(11216.5) 
print(i)

运算结果:
123
1.2
1.2
11216.5
11216.5

2,all ()

循环参数

    如果每个元素都为真,那么all的返回值为真

假: 0,None,"",[],(),{},  ==>   总结出;0,None,空值 为假

示例:

all(['a', 'b', 'c', 'd'])  #列表list,元素都不为空或0
True
all(['a', 'b', '', 'd'])  #列表list,存在一个为空的元素
False
all([0, 1,2, 3])  #列表list,存在一个为0的元素
False

all(('a', 'b', 'c', 'd'))  #元组tuple,元素都不为空或0
True
all(('a', 'b', '', 'd'))  #元组tuple,存在一个为空的元素
False
all((0,1,2,3,4))  #元组tuple,存在一个为0的元素
False
all([]) # 空列表
True
all(()) # 空元组
True

 

3,any()

只有有一个真,则为真

def any(iterable):
   for i in iterable:
       if  i:
           return False
   return True

示例:

any(['a', 'b', 'c', 'd'])  #列表list,元素都不为空或0
True

any(['a', 'b', '', 'd'])  #列表list,存在一个为空的元素
True

any([0, '', False])  #列表list,元素全为0,'',false
False
 
any(('a', 'b', 'c', 'd'))  #元组tuple,元素都不为空或0
True

any(('a', 'b', '', 'd'))  #元组tuple,存在一个为空的元素
True

 any((0, '', False))  #元组tuple,元素全为0,'',false
False
 
any([]) # 空列表
False

any(()) # 空元组
False

 

4,divmod(a,b)函数

divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数

li = divmod(10,3)
print(li)
运算结果:
(3, 1)

5,eval()

可以执行一个字符串形式的表达式;简单的表达式,可以给算出来

ret = eval("122+45+53")
print(ret)
运算结果:
220


ret = eval("a + 60",{"a":99})
print(ret)
运算结果:
159

6,exec()

可以执行py代码 ;不会返回值,直接输出结果

 exec("print(\"hello, world\")")
运算结果:
hello, world

7,filter()  

对于序列中的元素进行筛选,最终获取符合条件的序列(需要循环)

(函数,可迭代的对象)   过滤器  

示例:

法一:
def f1(x):
if x >22:
return True
else:
return False

ret = filter(f1,[11,22,33,44])

  for i in ret:
    print(i)

法二:
def
f1(x): return x > 22 ret = filter(lambda x: x > 22, [11,22,33,44]) for i in ret: print(i) 运算结果: 33 44

8,map()

(函数,可以迭代的对象,让元素统一操作)

示例:

def f(x):
    return x * x

r = map(f, [1, 2, 3, 4, 5, 6])
list(r)

[1, 4, 9, 16, 25, 36]

****************
def f1(x):
if x % 2 ==1:
return x + 100
else:
return x

ret = map(lambda x: x + 100 if x % 2 ==1 else x, [1,2,3,4])
# print(ret)
for i in ret:
print(i)

 9,globals()

 获取全局变量  globals()对象的值能修改

def f1():
    name = 123
    print(globals(name))

10,locals()

获取局部变量  locals()对象的值不能修改

def f1():
    name = 123
    
    print(locals(name))

11,isinstance()

判断对象是否存在某个类创建的

a = 10

def b():
    pass

print (isinstance(a,(int,str)))
print (isinstance(a,(float,str)))
print (isinstance(b,(str,int)))

class c:
    pass

obj = c()

print (isinstance(obj,(c,int)))

运算结果:
True
False
False
True

12,__repr__

ascii对象的类中找 __repr__,获取其返回值

class Foo:
    def __repr__(self):
        return "hello"
        
obj = Foo()
r = ascii(obj)
print(r)
运算结果:
hello

 13,iter()

迭代方法,依次取值

obj = iter([11,22,33,44])
print(obj)
r1 = next(obj)  #next,取下一个值,一个变量里的值可以一直往下取,直到没有就报错
print(r1)

r2 = next(obj) 
print(r2)

r3 = next(obj)
print(r3)
运算结果:
11
22
33

14,max()

取最大值

li = ([11,22,33,44,1])
r = max(li)
print(r)
运算结果:
44

15,min()

取最小值

li = ([11,22,33,44,1])
r = min(li)
print(r)
运算结果:
1

16,pow(x,y)

求次方

i = pow(2,10)
print(i)
运算结果:
1024

17,sum()

求和

r = sum([11,22,33,44])    
print(r)
运算结果:
110

 18,round 四舍五入

 ret = round(4.8)
 print(ret)

 

 

19,zip()

zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表

a = [1,2,3]
b = [4,5,6]

r = zip(a,b) # zip,让a,b值1 1对应
for i in r:

    print(i)
运算结果:
(1, 4)
(2, 5)
(3, 6)

20,import()

导入

import math       #入导math模块
math.floor()        #调用math模块中的floor()函数



python from使用方法例如:
from math import floor     #导入math模块中的floor函数方法
floor()                         #调用floor()函数方法

21,sort()

排序

li = [11,33,55,22,55,]
print(li)
li.sort()
print(li)
运算结果:
[11, 33, 55, 22, 55]
[11, 22, 33, 55, 55]

 22,flush()

刷新内部缓冲区

示例:

f = open("foo.txt", "wb")
print ("Name of the file:hello word "), f.name

f.flush()

f.close()
运算结果:
Name of the file:hello word 

23,read()

读取文件内容   (给read加上一个参数,指定要读取的最大行数)

示例:

f = open("a_f.dat","rb")
data = f.read(10000)
f.close()

24,readline()

readline判断文件读取结束的方法

示例:

filename = raw_input('Enter your file name')  #输入要遍历读取的文件路径及文件名
file = open(filename,'r')
done = 0
while not  done:
        aLine = file.readline()
        if(aLine != ''):
            print aLine,
        else:
            done = 1
file.close()   #关闭文件

 

 25,hash

hash对key的优化,相当于给输出一种哈希值

li = "sdglgmdgongoaerngonaeorgnienrg"
print(hash(li))

26,callable

callable表示一个对象是否可执行

 def f1():        #看这个函数能不能执行,能发挥True     return 123 f1() r = callable(f1) print(r)

 

进制

r = bin(11) #二进制
print(r)


r = oct(8) #八进制
print(r)


i = int(10)  #十进制
print(i)


r = hex(14)  #十六进制
print(r)

运算结果:
0b1011
0o10
10
0xe

进制转换

示例:

int(10)
i = int('0b11',base=2) #二进制转换十进制
print(i)

i = int('0o11',base=8) #八进制转换十进制
print(i)

i = int('0xe',base=16) #十六进制转换十进制
print(i)

运算结果:
3
9
14

 

字节,字符串

示例:

#bytes("xxxx",encoding="utf-8")

i = bytes("你好,世界",encoding="utf-8")
print(i)

运算结果:
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'

chr() 数字转换成字符 # 只适用在ascii中

示例:

c = chr(253)
print(c)
运算结果:
y

ord() 字符转换成数字# 只适用在ascii中

示例:

c = ord('x')
print(c)
运算结果:
120

 

随机数:

import random

print (random.random())
print (random.randint(1,2))
print (random.randrange(1,10))

 

随机验证码:

import random
temp = ""
for i in range(6):
    #生成 0—4的随机数
    num = random.randrange(0,4)
    # 如果随机数是1 或 3,那么就在验证码中生成一个 0—9的随机数字
    #否则,验证码中生成一个随机字母
    if num == 3 or num== 1:
        rad2 = random.randrange(0,10)
        temp = temp + str(rad2)
    else:
        rad1 = random.randrange(65,91)
        c1 = chr(rad1)
        temp = temp + c1
print(temp)

 

文件操作

一,打开文件

二,操作文件

三,关闭文件

 

open (文件名,模式,编码)

格式:

f =open("文件名""r")  # r  只读模式

data = f.read()

f.close()

peint(data)

打开文件的模式:

普通方式(python内部自动转换)

1)只读模式,r

f = open("ha.log","r")
f.write("kdjaskjskasdksjdaksj")
f.close

2)只写模式,w 【不可读,文件不存在则创建;存在则清空文件内容再写入】

f = open("ha1.log","w")
f.write("sdhjf43dk3rfk")
f.close()

3)只写模式,x 【不可读;文件不存在则创建;文件存在则报错】

f = open("ha2.log","w")
f.write("dahhadiu3528")
f.close()

4)追加模式【不可读;不存在的则创建;存在则追加到末尾】

f = open("ha2.log","a")
f.write("666jjjksk")
f.close()

 

以字节的方式(二进制的方式)“b”

1)只读模式,rb 【文件不存在则创建;文件存在则清空内容】

f = open("ha.log","rb")
data = f.read()
f.close()
print(data)
str_data = str(data, encoding="utf-8")
print(str_data)

2)只读模式,wb 【文件不存在则创建;存在则清空内容】

f = open("ha.log","wb")
str_data = "中国人"
bytes_data = bytes(str_data, encoding="utf-8")
f.write(bytes_data)
f.close()

 

同时读写文件 “+”

1)r+ 开始向后读,写时追加,指针调到最后

 

2)w+,先清空,再写,才可以读。写,指针到最后

 

3)x+如果文件存在则报错

 

 

4)a+,打开的同时指针已经移到最后,追加在最后

 

 

f.tell()#获取指针的位置
f.seek(num) #调整指针位置
f.write("")#写入
f.read("") # 读取

 

操作

  1 class file(object)
  2     def close(self): # real signature unknown; restored from __doc__
  3         关闭文件
  4         """
  5         close() -> None or (perhaps) an integer.  Close the file.
  6          
  7         Sets data attribute .closed to True.  A closed file cannot be used for
  8         further I/O operations.  close() may be called more than once without
  9         error.  Some kinds of file objects (for example, opened by popen())
 10         may return an exit status upon closing.
 11         """
 12  
 13     def fileno(self): # real signature unknown; restored from __doc__
 14         文件描述符  
 15          """
 16         fileno() -> integer "file descriptor".
 17          
 18         This is needed for lower-level file interfaces, such os.read().
 19         """
 20         return 0    
 21  
 22     def flush(self): # real signature unknown; restored from __doc__
 23         刷新文件内部缓冲区
 24         """ flush() -> None.  Flush the internal I/O buffer. """
 25         pass
 26  
 27  
 28     def isatty(self): # real signature unknown; restored from __doc__
 29         判断文件是否是同意tty设备
 30         """ isatty() -> true or false.  True if the file is connected to a tty device. """
 31         return False
 32  
 33  
 34     def next(self): # real signature unknown; restored from __doc__
 35         获取下一行数据,不存在,则报错
 36         """ x.next() -> the next value, or raise StopIteration """
 37         pass
 38  
 39     def read(self, size=None): # real signature unknown; restored from __doc__
 40         读取指定字节数据
 41         """
 42         read([size]) -> read at most size bytes, returned as a string.
 43          
 44         If the size argument is negative or omitted, read until EOF is reached.
 45         Notice that when in non-blocking mode, less data than what was requested
 46         may be returned, even if no size parameter was given.
 47         """
 48         pass
 49  
 50     def readinto(self): # real signature unknown; restored from __doc__
 51         读取到缓冲区,不要用,将被遗弃
 52         """ readinto() -> Undocumented.  Don't use this; it may go away. """
 53         pass
 54  
 55     def readline(self, size=None): # real signature unknown; restored from __doc__
 56         仅读取一行数据
 57         """
 58         readline([size]) -> next line from the file, as a string.
 59          
 60         Retain newline.  A non-negative size argument limits the maximum
 61         number of bytes to return (an incomplete line may be returned then).
 62         Return an empty string at EOF.
 63         """
 64         pass
 65  
 66     def readlines(self, size=None): # real signature unknown; restored from __doc__
 67         读取所有数据,并根据换行保存值列表
 68         """
 69         readlines([size]) -> list of strings, each a line from the file.
 70          
 71         Call readline() repeatedly and return a list of the lines so read.
 72         The optional size argument, if given, is an approximate bound on the
 73         total number of bytes in the lines returned.
 74         """
 75         return []
 76  
 77     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
 78         指定文件中指针位置
 79         """
 80         seek(offset[, whence]) -> None.  Move to new file position.
 81          
 82         Argument offset is a byte count.  Optional argument whence defaults to
 83 (offset from start of file, offset should be >= 0); other values are 1
 84         (move relative to current position, positive or negative), and 2 (move
 85         relative to end of file, usually negative, although many platforms allow
 86         seeking beyond the end of a file).  If the file is opened in text mode,
 87         only offsets returned by tell() are legal.  Use of other offsets causes
 88         undefined behavior.
 89         Note that not all file objects are seekable.
 90         """
 91         pass
 92  
 93     def tell(self): # real signature unknown; restored from __doc__
 94         获取当前指针位置
 95         """ tell() -> current file position, an integer (may be a long integer). """
 96         pass
 97  
 98     def truncate(self, size=None): # real signature unknown; restored from __doc__
 99         截断数据,仅保留指定之前数据
100         """
101         truncate([size]) -> None.  Truncate the file to at most size bytes.
102          
103         Size defaults to the current file position, as returned by tell().
104         """
105         pass
106  
107     def write(self, p_str): # real signature unknown; restored from __doc__
108         写内容
109         """
110         write(str) -> None.  Write string str to file.
111          
112         Note that due to buffering, flush() or close() may be needed before
113         the file on disk reflects the data written.
114         """
115         pass
116  
117     def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
118         将一个字符串列表写入文件
119         """
120         writelines(sequence_of_strings) -> None.  Write the strings to the file.
121          
122         Note that newlines are not added.  The sequence can be any iterable object
123         producing strings. This is equivalent to calling write() for each string.
124         """
125         pass
126  
127     def xreadlines(self): # real signature unknown; restored from __doc__
128         可用于逐行读取文件,非全部
129         """
130         xreadlines() -> returns self.
131          
132         For backward compatibility. File objects now include the performance
133         optimizations previously implemented in the xreadlines module.
134         """
135         pass
136 
137 2.x
2.x
  1 class TextIOWrapper(_TextIOBase):
  2     """
  3     Character and line based layer over a BufferedIOBase object, buffer.
  4     
  5     encoding gives the name of the encoding that the stream will be
  6     decoded or encoded with. It defaults to locale.getpreferredencoding(False).
  7     
  8     errors determines the strictness of encoding and decoding (see
  9     help(codecs.Codec) or the documentation for codecs.register) and
 10     defaults to "strict".
 11     
 12     newline controls how line endings are handled. It can be None, '',
 13     '\n', '\r', and '\r\n'.  It works as follows:
 14     
 15     * On input, if newline is None, universal newlines mode is
 16       enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
 17       these are translated into '\n' before being returned to the
 18       caller. If it is '', universal newline mode is enabled, but line
 19       endings are returned to the caller untranslated. If it has any of
 20       the other legal values, input lines are only terminated by the given
 21       string, and the line ending is returned to the caller untranslated.
 22     
 23     * On output, if newline is None, any '\n' characters written are
 24       translated to the system default line separator, os.linesep. If
 25       newline is '' or '\n', no translation takes place. If newline is any
 26       of the other legal values, any '\n' characters written are translated
 27       to the given string.
 28     
 29     If line_buffering is True, a call to flush is implied when a call to
 30     write contains a newline character.
 31     """
 32     def close(self, *args, **kwargs): # real signature unknown
 33         关闭文件
 34         pass
 35 
 36     def fileno(self, *args, **kwargs): # real signature unknown
 37         文件描述符  
 38         pass
 39 
 40     def flush(self, *args, **kwargs): # real signature unknown
 41         刷新文件内部缓冲区
 42         pass
 43 
 44     def isatty(self, *args, **kwargs): # real signature unknown
 45         判断文件是否是同意tty设备
 46         pass
 47 
 48     def read(self, *args, **kwargs): # real signature unknown
 49         读取指定字节数据
 50         pass
 51 
 52     def readable(self, *args, **kwargs): # real signature unknown
 53         是否可读
 54         pass
 55 
 56     def readline(self, *args, **kwargs): # real signature unknown
 57         仅读取一行数据
 58         pass
 59 
 60     def seek(self, *args, **kwargs): # real signature unknown
 61         指定文件中指针位置
 62         pass
 63 
 64     def seekable(self, *args, **kwargs): # real signature unknown
 65         指针是否可操作
 66         pass
 67 
 68     def tell(self, *args, **kwargs): # real signature unknown
 69         获取指针位置
 70         pass
 71 
 72     def truncate(self, *args, **kwargs): # real signature unknown
 73         截断数据,仅保留指定之前数据
 74         pass
 75 
 76     def writable(self, *args, **kwargs): # real signature unknown
 77         是否可写
 78         pass
 79 
 80     def write(self, *args, **kwargs): # real signature unknown
 81         写内容
 82         pass
 83 
 84     def __getstate__(self, *args, **kwargs): # real signature unknown
 85         pass
 86 
 87     def __init__(self, *args, **kwargs): # real signature unknown
 88         pass
 89 
 90     @staticmethod # known case of __new__
 91     def __new__(*args, **kwargs): # real signature unknown
 92         """ Create and return a new object.  See help(type) for accurate signature. """
 93         pass
 94 
 95     def __next__(self, *args, **kwargs): # real signature unknown
 96         """ Implement next(self). """
 97         pass
 98 
 99     def __repr__(self, *args, **kwargs): # real signature unknown
100         """ Return repr(self). """
101         pass
102 
103     buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
104 
105     closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
106 
107     encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
108 
109     errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
110 
111     line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
112 
113     name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
114 
115     newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
116 
117     _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
118 
119     _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
120 
121 3.x
3.x

 

 

关闭文件

with open ("ha.log","r") as f :
f.read()

同时打开两个文件(2.7以上版本)

with open('log1','r') as obj1, open('log2', 'r') as obj2:
    pass



with open('源文件','r') as obj1, open('新文件', 'w') as obj2:
    for line in obj1:
        obj2.write(line)

 

详细请参考:http://www.cnblogs.com/wupeiqi/articles/4943406.html

      http://www.cnblogs.com/wupeiqi/articles/4911365.html