v = [lambda :x for x in range(10)] print(v) #[lambda :x,lambda :x....]10个匿名函数 print(v[0]) #lambda :x print(v[0]()) #9
v = (lambda :x for x in range(10)) print(v) #生成器 # print(v[0]) #报错:生成器不能索引取值 # print(v[0]()) #报错:生成器不能索引取值 print(next(v)) #lambda :x print(next(v)()) #1
def extendList(val, list=[]): list.append(val) return list list1 = extendList(10) list2 = extendList(123, []) list3 = extendList('a') print('list1=%s' % list1) # list1=[10,'a'] print('list2=%s' % list2) # list2=[123] print('list3=%s' % list3) # list3=[10,'a']
def add(a, b): return a + b def test(): for i in range(4): yield i g = test() # 生成器 for n in [2, 10]: g = (add(n, i) for i in g)# 生成器 print(list(g))#[20,21,22,13] #n=2: # 循环体执行时i对应的值 (0,1,2,3) # 循环体执行之后:g类似于[add(n, 0),add(n, 1),add(n, 2),add(n, 3)] #n=10时: # 循环体执行时i 的值 (10,11,12,13)-----对n=2循环之后的g进行取值 # 循环体执行之后:list(g)=(add(n, 10),add(n, 11),add(n, 12),add(n, 13))
li = [7,-8,5,4,0,-2,-5] print(sorted(li,key=lambda x:(x<0,abs(x))))
print(5/2) print(5.0/2) print(5/2.0) print(5.0/2.0) print(5//2) print(5.0//2) print(5//2.0) print(5.0//2.0) #python3中 2.5 2.5 2.5 2.5 2 2.0 2.0 2.0 #python2中 2 2.5 2.5 2.5 2 2.0 2.0 2.0
dic={x:y for x in ['Male','Female'] for y in ['Red','Black']} print(dic) # {'Male':'Black','Female':'Black'} li=[(x,y) for x in ['Male','Female'] for y in ['Red','Black']] print(li) #[('Male','Red'),('Male','Black'),('Female','Red'),('Female','Black')]
li=[[]]*5 #[[], [], [], [], []] li[0].append(1) #[[1], [1], [1], [1], [1]] li[3].append(0) #[[1, 0], [1, 0], [1, 0], [1, 0], [1, 0]] li.append(8) #[[1, 0], [1, 0], [1, 0], [1, 0], [1, 0],8] print(li)
t=((1,2))*5 #(1, 2, 1, 2, 1, 2, 1, 2, 1, 2) t1=((1,2),)*5 #((1, 2), (1, 2), (1, 2), (1, 2), (1, 2)) print(t) print(t1)
for x in range(5): pass print(x) #4 def f(): x = 0 for i in range(5): x += i f() print(x)