Python8--匿名函数、变量交换

  1 #匿名函数
  2 nums = [ 123 , 12 , 342 , 23 , 543 , 45 , 34 , 4 , 4 , 5 , 34 , 345 ]
  3 nums.sort() # 排序
  4 print (nums)
  5
  6 nums.reverse() # 倒序
  7 print (nums)
  8
  9 infors = [{ 'name' : 'jack' , 'age' : 10 },{ 'name' : 'ben' , 'age' : 20 },{ 'name' : 'alex' , '     age' : 16 }]
 10 infors.sort(key = lambda x:x[ 'name' ]) # 按‘name’的值来比较
 11 print (infors)
 12
 13 def test (a,b,func):
 14     result = func(a,b)
 15     return result
 16
 17 num = test( 12 , 13 , lambda x,y:x+y) # x指向12 ,y指向13,返回 x+y
 18 print (num)
 19
 20 def test2 (a,b,func):
 21     result = func(a,b)
 22     return result
 23
 24 func_new = input ( '请输入一个匿名函数: \n ' ) # 输入一个匿名函数,如 lambda x,y     :x*y
 25 func_new = eval (func_new)
 26 num = test2( 123 , 234 ,func_new)
 27 print (num)


  1 # 两个变量的交换
  2 a = 1
  3 b = 2
  4 print ( 'a=%d,b=%d' %(a,b))
  5
  6 #第一种
  7 c = 0
  8 c = a
  9 a = b
 10 b = c
 11 print ( 'a=%d,b=%d' %(a,b))
 12
 13 #第二种
 14 a = a+b
 15 b = a-b
 16 a = a-b
 17 print ( 'a=%d,b=%d' %(a,b))
 18
 19 #第三种
 20 a,b = b,a
 21 print ( 'a=%d,b=%d' %(a,b))
 22
 23 n = [ 10 ] # 列表是可变数据类型 最后值都是[10,10] ,若n= 10 则不可改变
 24 def test (num):
 25     num +=num
 26 #   num = num + num  # 输出的值为[10.10],但不会改变n的值
 27     print (num)
 28 test(n)
 29 print (n)

猜你喜欢

转载自blog.csdn.net/csdn15150525313/article/details/78494706
今日推荐