列表解析
- 定义:
- 操作和处理一个序列(或其他的可迭代对象)来创建一个新的列表
- 在需要改变列表而不是需要新建某列表时,可以使用列表解析。
- 表达式如下:
[expr for iter_var in iterable] //for循环可以嵌套
[expr for iter_var in iterable if cond_expr] //加入了判断条件
- 用例 :
-
列表去重
l1 = [1,1,2,4,3,4,3,5]
l2 = []
[l2.append(i) for i in l1 if not i in l2] -
元组(生成器,后续介绍)
iter = ( x**2 for i in range(10) if x%2 ==0 )
print iter //<generator object <genexpr> at 0x10da37af0> -
多重循环
print [(x,y)for x in (1,2,3,4) for y in (10,15,3,22) if x*y >25] -
效率提升
import timeresults = [] maxloops = 100 ranges = 100 min_time = 100000 total_time = 0.0 is_forloop = input('Please input 0 or 1:') for loops in range(maxloops): start_clock = time.clock() if is_forloop: for i in range(ranges): for j in range(ranges): if (i*j) > (i+j): results.append((i,j,i*j)) else: results = [(i,j,i*j) for i in range(ranges) for j in range(ranges) if (i*j)>(i+j)] end_clock = time.clock() run_time = end_clock - start_clock total_time = total_time + run_time if run_time < min_time: min_time = run_time print 'The results is: ',results print 'The fastest loop time is: ',min_time print 'The avrage loop time is: ', (total_time)/maxloops
-
异常处理
-
try...except
/try...except...finally
- try后语句如果有异常,执行except语句
- 无论异常发生与否都会执行finally语句内容
-
raise error(message)
- 主动触发异常,输出错误信息message
-
assert condition, message
- 条件满足时,输出错误信息message
- 举例
a[1] #NameError
a=2;a[1] #TypeError
a=[2];a[9] #IndexError
a={};a[1] #KeyError
- 综合例子
try:
a=[0,1]
print a[1]
# raise IndexError('Error!')
assert a[1]==0, 'Assert error!'
except Exception,e:
print e
finally:
print 'Finally excute!'
参考资料
网友评论