python 备忘(内置函数)【列表推导式,try】【iter 和 next】
- iter 和 next
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
# 获得下一个值:
x = next(it)
print(x)
except StopIteration:
# 遇到StopIteration就退出循环
break
- python的一些std,错误Exception处理
import traceback
import sys
try:
raise ValueError('this is a exp')
except Exception as ex:
ex_type, ex_val, ex_stack = sys.exc_info()
print(ex_type)
print(ex_val)
print(ex_stack)
for stack in traceback.extract_tb(ex_stack):
print(stack)
and or 赋值相关操作
优先级or要低,n > 1 and 'errorClass'中 n >1 为true 就看and 后面的 errorClass也为true 整个就是true不用看or后面的,就返回了errorClass
'''
看到HTMLTestRunner有个表达式
'''
n =2
style = n > 1 and 'errorClass' or n > 0 and 'failClass' or 'passClass'
print(style) # passClass
'''
简化版
'''
test = '' or [] or {}
print(test) # {}
- callable函数
对于函数、方法、lambda 函式、 类以及实现了 _call_ 方法的类实例, 它都返回 True。
>>>callable(0)
False
>>> callable("runoob")
False
>>> def add(a, b):
... return a + b
...
>>> callable(add) # 函数返回 True
True
>>> class A: # 类
... def method(self):
... return 0
...
>>> callable(A) # 类返回 True
True
>>> a = A()
>>> callable(a) # 没有实现 __call__, 返回 False
False
>>> class B:
... def __call__(self):
... return 0
...
>>> callable(B)
True
>>> b = B()
>>> callable(b) # 实现 __call__, 返回 True
True
next、iter的应用
next、iter组合起来的用发
1.
def test(context=False, **kwargs):
k, v = next(iter(kwargs.items()))
print(k,v) # 可以获取到第一参数的kv值
k,v ,g= kwargs.items() # kwargs 传入3个这里就要写3个了。。。
print(k[0],k[1])
property
title
1 class Foo:
2 def get_AAA(self):
3 print('get的时候运行我啊')
4
5 def set_AAA(self,value):
6 print('set的时候运行我啊')
7
8 def delete_AAA(self):
9 print('delete的时候运行我啊')
10 AAA=property(get_AAA,set_AAA,delete_AAA) #内置property三个参数与get,set,delete一一对应
11
12 f1=Foo()
13 f1.AAA
14 f1.AAA='aaa'
15 del f1.AAA
dir
不太理解为啥叫dir
python的os操作
lambda (lambda arguments : expression)
常用的场景
#1
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
#2
now = lambda : time.time()
start = now()
#3
x = lambda a, b : a * b
print(x(5, 6))
#来个难点的
def multipliers():
return [lambda x: i * x for i in range(4)]
print([m(2) for m in multipliers()])
python 数据类型,以及数据类型转换
Python有五个标准的数据类型:
Numbers(数字)
String(字符串)
List(列表)
Tuple(元组)
Dictionary(字典)
类型的转换:
int(x [,base ]) 将x转换为一个整数
long(x [,base ]) 将x转换为一个长整数
float(x ) 将x转换到一个浮点数
complex(real [,imag ]) 创建一个复数
str(x ) 将对象 x 转换为字符串
repr(x ) 将对象 x 转换为表达式字符串
eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s ) 将序列 s 转换为一个元组
list(s ) 将序列 s 转换为一个列表
chr(x ) 将一个整数转换为一个字符
unichr(x ) 将一个整数转换为Unicode字符
ord(x ) 将一个字符转换为它的整数值
hex(x ) 将一个整数转换为一个十六进制字符串
oct(x ) 将一个整数转换为一个八进制字符串
python中的else的使用
#1 if
#2 while
当while 不成立 -> else
#3 for
当for 结束 -> else
#4 try
当不报错 -> else
```python
#实际应用场景 出现异常多执行几次,成功跳出循环
for i in range(20):
challenge_pin = get_challenge_pin(url)
if challenge_pin is not None:
pin = challenge_pin + "xx" + challenge_pin
try:
password = my_js_md5(s=pin)
get_login_cookie(url,password)
except:
print("get challenge pin failed ,please rerun !")
continue
else:
turn_on_off(2,'off')
rst = runCommand(cmd)
break
# finally使用
try:
print “input an integer"
a = raw_input(">")
print "input an integer"
b = raw_input(">")
result = int(a)/int(b)
except ValueError:
print "please input the correct type of value"
except ZeroDivisionError:
print " 0 can not be divided"
else:
print "good job!"
finally:
print "the calculation finished"
python 指定位数 位数补齐
title
print('789'.rjust(10,'0')) # 0000000789
print('789'.zfill(10)) # 0000000789
print('%010d'%(789)) # 0000000789
try 用法
#1导入库
try:
import paramiko
except ImportError:
raise ImportError(
'Importing Paramiko library failed. '
'Make sure you have Paramiko installed.'
)
enumerate
for idx, fore_kw in enumerate(kw_list):
logger.info(fore_kw.getAttribute('name'))
if fore_keyword is None or fore_kw.getAttribute('name') == fore_keyword:
try:
if kw_list[idx + 1].getAttribute('name') == keyword:
starttimes = []
endtimes = []
statuses = []
runtimes = []
for status in kw_list[idx + 1].childNodes:
if status.nodeName == 'status':
starttime = status.getAttribute('starttime')
starttime_arry = time.strptime(starttime.split('.')[0], '%Y%m%d %H:%M:%S')
starttime_stamps = int(time.mktime(starttime_arry))
endtime = status.getAttribute('endtime')
endtime_arry = time.strptime(endtime.split('.')[0], '%Y%m%d %H:%M:%S')
endtime_stamps = int(time.mktime(endtime_arry))
runtime = endtime_stamps - starttime_stamps
# logger.info('Shutdown:', starttime, 'Up:', endtime, 'Run Time:', runtime)
logger.info('Shutdown:%s Up:%s RRU StartUp Time: %s' % (starttime, endtime, runtime))
status = status.getAttribute('status')
starttimes.append(starttime)
endtimes.append(endtime)
statuses.append(status)
runtimes.append(runtime)
return starttimes, endtimes, runtimes, statuses
except IndexError:
continue
列表推导式(2个for循环)
nums = [[1, 3, 5, 7], [2, 4, 6, 8]]
# 使上述nums中的每个数字都取出来,放到一个新列表中,用到2个for循环
new_nums = []
for nums_a in nums:
# print(nums_a)
for i in nums_a:
new_nums.append(i)
print("new_nums的值为:{}".format(new_nums))
# 列表推导式
new_num = [i for nums_a in nums for i in nums_a]
# 从左至右,分别是外层循环到内层循环;先把里面的2个小列表遍历一遍,然后再遍历每个小列表的数字;
# 最后的表示结果的变量,写在最左侧
print("new_num的值为:{}".format(new_num))
- 字典推导式
name = ["张三", "李四", "王五", "李六"]
sign = ["白羊座", "双鱼座", "狮子座", "处女座"]
dict1 = {i : j for i, j in zip(name, sign)} # {'张三': '白羊座', '李四': '双鱼座', '王五': '狮子座', '李六': '处女座'}
- zip 应用在字符串上
string = 'LooksGood'
print(list(zip(' ' + string, string, string[1:] + ' ')))
# [(' ', 'l', 'o'), ('l', 'o', 'o'), ('o', 'o', 'k'), ('o', 'k', 's'), ('k', 's', 'G'), ('s', 'G', 'o'), ('G', 'o', 'o'), ('o', 'o', 'd'), ('o', 'd', ' ')]