for循环和lambda
list1 = [0, 1, 3, 10, 12]
aa = [x + 1 for x in list1]
print("aa=", aa)
bb = [x * 2 for x in list1]
print("bb=", bb)
cc = [x for x in list1 if x % 3 == 0]
print("cc=", cc)
pp = list(filter(lambda x: x if x % 3 == 0 else None, list1))
print("pp=", pp)
tt = list(filter(lambda x: not (x % 3), range(1, 100)))
print("tt=", tt)
rr = [x for x in range(1, 100) if x % 3 == 0]
print("rr=", rr)
list2=[1,3,5,7,9]
list3=[2,4,6,8,11]
gg=list(zip(list2,list3))
print("gg=", gg)
yy=list(map(lambda x,y:[x,y],list2,list3))
print("yy=", gg)
mm =(lambda x: list1[x] - list1[x-1])
print("mm=", mm(2))
groupby分组
from operator import itemgetter
from itertools import groupby
l1={'name':'aaa','City':'广州','age':20}
l2={'name':'bbb','City':'深圳','age':26}
l3={'name':'ccc','City':'广州','age':23}
l4={'name':'ddd','City':'惠州','age':24}
l5={'name':'eee','City':'深圳','age':25}
l6={'name':'fff','City':'广州','age':26}
l7=[l1,l2,l3,l4,l5,l6]
l7.sort(key=itemgetter('City'))
ls = groupby(l7,itemgetter('City'))
for value,groups in ls:
for group in groups:
print (value,group)
from itertools import groupby
l8=[45, 70, 55, 66, 87, 98, 100, 88, 96, 68]
def sorts(valuess):
if valuess < 60:
return '不及格'
elif valuess >= 90:
return '优秀'
else:
return '及格'
print ([(value,list(group)) for value,group in groupby(sorted(l8),key=sorts)])
输出不在列表1范围内的数
from itertools import groupby
list1 = [0, 1, 3, 10, 12]
list2=[]
list3=[]
for i in range(0, 100):
if i not in list1:
list2.append(i)
fun = lambda x: x[1] - x[0]
for k, g in groupby(enumerate(list2), fun):
l1 = [j for i, j in g]
if len(l1) > 1:
scop = str(min(l1)) + '-' + str(max(l1))
else:
scop = l1[0]
list3.append(scop)
print(list3)