#zip方法
l = [1,2,3] l2 = ['a','b','c'] l3 = ('*','**',[1,2]) l4 = {'k1':1,'k2':2} for i in zip(l,l2,l3,l4): print(i)
#filter
def is_odd(x): return x %2 == 1 ret = filter(is_odd,[1,4,5,7,8,12]) for i in ret: print(i) 1 5 7
#过滤字符串
def is_str(s): return type(s)==str ret = filter(is_str,[1,4,5,'hello',7,8,'world',12]) for i in ret: print(i) hello world
#删除None和空字符串
def is_str(s): if type(s) != int: return s and str(s).strip() ret = filter(is_str,[1,4,5,'hello',' ',[],None,7,8,'world',12]) for i in ret: print(i)
利用filter过滤出1-100中平方根的整数的数,
from math import sqrt
def func(num):
res = sqrt(num)
return res%1 == 0
ret = filter(func,range(1,101))
for i in ret:
print(i)
#map方法 执行一边abs
ret = map(abs,[1,-2,-5,3]) print(ret) for i in ret: print(i) 1 2 5 3
#总结
# filter 执行了filter之后的结果的集合 <=执行之前的个数
# filter只管筛选,不会改变原来的值
# map 执行前后元素个数不变
# 值可能发生改变
# sorted()
l = [1,-4,6,5,-10] print(sorted(l)) #产生新的列表,不改变源列表,占内存 print(l)
print(sorted(l,reverse=True))
[-10, -4, 1, 5, 6]
[1, -4, 6, 5, -10]
[6, 5, 1, -4, -10]
列表长度从长到短排序
l = [' ',[1,2],'hello world'] new_l = sorted(l,key=len,reverse=True) print(new_l) ['hello world', ' ', [1, 2]]