python 进阶笔记

前言

最近正准备写一个软件工程的大作业web渗透测试信息收集框架,最近正在看别人的代码,发现一些很python(很cool)的写法,所以在这里整理一波,以后遇到了再往这里写吧。

正文

多个for连写

可以用在两个可迭代对象的组合。

>>> str1 = "123"
>>> str2 = "abc"
>>> for (i,a) in ((i,a) for i in str1 for a in str2):
...     print(i,a)
... 
1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c
>>> a = ((i, a) for i in str1 for a in str2)
>>> a
<generator object <genexpr> at 0x7f5ad91114c0>
>>> for i in a:
...  print(i)
... 
('1', 'a')
('1', 'b')
('1', 'c')
('2', 'a')
('2', 'b')
('2', 'c')
('3', 'a')
('3', 'b')
('3', 'c')

三目运算 if else

一般情况下求求绝对值的写法是这样的

>>> x = -1 
>>> if x > 0:
...     print(x)
... else:
...     print(-x)
... 
1

python还支持类似三目运算符一样的写法

>>> x = x if (x > 0) else -x
>>> x = -1
>>> x = x if (x > 0) else -x
>>> x
1

x = if为真的值 if (判断条件) else if为假的值

map()函数的使用

map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。

map(…)
map(function, sequence[, sequence, …]) -> list
Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).

比如需要求0-10的平方,一般的写法都是使用for循环,如果使用map(),只需要一行代码

map(函数, 序列对象)
>>> numbers = range(11)
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> map(lambda x : x**2, numbers)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

reduce()函数

reduce函数的作用和filter的类似,reduce把一个函数作用在一个序列[x1, x2, x3…]上,这个函数必须接收两个参数.

reduce(…)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.

举个例子,比如实现累加

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> reduce(lambda x,y:x+y, numbers)
55

filter()函数

Python内建的filter()函数用于过滤序列。

filter(…)
filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.

>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> filter(lambda x:x>5, numbers)
[6, 7, 8, 9, 10]

zip()函数

zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压)。

zip(…)
zip(seq1 [, seq2 […]]) -> [(seq1[0], seq2[0] …), (…)]
Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.

举个例子

>>> a = (1,2,3)
>>> b = (4,5,6)
>>> zip(a,b)
[(1, 4), (2, 5), (3, 6)]
>>> #长度不等时,取长度最短的
>>> a = (1,2,3)
>>> b = (4,5,6,7)
>>> zip(a,b)
[(1, 4), (2, 5), (3, 6)]
>>> #非常有用,可以构造字典
... 
>>> a = (1,2,3)
>>> b = ("a","b","c")
>>> c = zip(a,b)
>>> dict(c)
{1: 'a', 2: 'b', 3: 'c'}

错误和异常

python中的标准异常有:

BaseException 所有异常的基类
SystemExit 解释器请求退出
KeyboardInterrupt 用户中断执行(通常是输入^C)
Exception 常规错误的基类
StopIteration 迭代器没有更多的值
GeneratorExit 生成器(generator)发生异常来通知退出
StandardError 所有的内建标准异常的基类
ArithmeticError 所有数值计算错误的基类
FloatingPointError 浮点计算错误
OverflowError 数值运算超出最大限制
ZeroDivisionError 除(或取模)零 (所有数据类型)
AssertionError 断言语句失败
AttributeError 对象没有这个属性
EOFError 没有内建输入,到达EOF 标记
EnvironmentError 操作系统错误的基类
IOError 输入/输出操作失败
OSError 操作系统错误
WindowsError 系统调用失败
ImportError 导入模块/对象失败
LookupError 无效数据查询的基类
IndexError 序列中没有此索引(index)
KeyError 映射中没有这个键
MemoryError 内存溢出错误(对于Python 解释器不是致命的)
NameError 未声明/初始化对象 (没有属性)
UnboundLocalError 访问未初始化的本地变量
ReferenceError 弱引用(Weak reference)试图访问已经垃圾回收了的对象
RuntimeError 一般的运行时错误
NotImplementedError 尚未实现的方法
SyntaxError Python 语法错误
IndentationError 缩进错误
TabError Tab 和空格混用
SystemError 一般的解释器系统错误
TypeError 对类型无效的操作
ValueError 传入无效的参数
UnicodeError Unicode 相关的错误
UnicodeDecodeError Unicode 解码时的错误
UnicodeEncodeError Unicode 编码时错误
UnicodeTranslateError Unicode 转换时错误
Warning 警告的基类
DeprecationWarning 关于被弃用的特征的警告
FutureWarning 关于构造将来语义会有改变的警告
OverflowWarning 旧的关于自动提升为长整型(long)的警告
PendingDeprecationWarning 关于特性将会被废弃的警告
RuntimeWarning 可疑的运行时行为(runtime behavior)的警告
SyntaxWarning 可疑的语法的警告
UserWarning 用户代码生成的警告

try…except…

一般的捕获异常的格式:

>>> while True:
...     try:
...             a = int(raw_input("enter number:"))
...     except ValueError as v:
...             print(v)
... 
enter number:2
enter number:a
invalid literal for int() with base 10: 'a'

except可以捕获0或者多个异常:

>>> while True:
...     try:
...             a = int(raw_input("enter number:"))
...     except ValueError,NameError:
...             pass

else子句的情况,其中的else子句中在except不执行的时候执行

>>> while True:
...     try:
...             a = int(raw_input("enter number:"))
...     except:
...             print("err")
...     else:
...             print("here is else")
... 
enter number:2
here is else
enter number:aa
err
enter number:

带finally子句,就是善后的,有了它,不管是try还是except,最后都要执行finally,一般用于资源释放。

assert断言

python assert断言是声明其布尔值必须为真的判定,如果发生异常就说明表达示为假。可以理解assert断言语句为raise-if-not,用来测试表示式,其返回值为假,就会触发异常。
可以在assert后面跟上任意判断条件,如果断言失败则会抛出异常。

Python多线程返回结果

import threading


class MyThread(threading.Thread):

    def __init__(self,func,args=()):
        super(MyThread,self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result  # 如果子线程不使用join方法,此处可能会报没有self.result的错误
        except Exception:
            return None


def foo(a,b,c):
    time.sleep(1)
    return a*2,b*2,c*2

st = time.time()
li = []
for i in xrange(4):
    t = MyThread(foo,args=(i,i+1,i+2))
    li.append(t)
    t.start()

for t in li:
    t.join()  # 一定要join,不然主线程比子线程跑的快,会拿不到结果
    print t.get_result()

et = time.time()
print et - st

运行结果

(0, 2, 4)
(2, 4, 6)
(4, 6, 8)
(6, 8, 10)
1.00099992759

list生成器

[x for x in os.listdir('.') if os.path.isdir(x)]

结果就是把当前目录的所有的目录添加到一个list中

['模板',
 '.npminstall_tarball',
 '.vmware',
 '项目',
 '.java',
 '.presage',
 '.sqlmap']

在这里插入图片描述

后言

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值