1、item
1 my_dict ={‘a‘:1,‘b‘:2} 2 print my_dict.items() 3 4 [(‘a‘, 1), (‘b‘, 2)]
2、keys,values
1 my_dict ={‘a‘:1,‘b‘:2} 2 print my_dict.keys() 3 print my_dict.values() 4 5 [‘a‘, ‘b‘] 6 [1, 2]
3、advanced list
1 new_list = [x for x in range(1,6)] 2 # => [1, 2, 3, 4, 5] 3 doubles = [x*2 for x in range(1,6)] 4 # => [2, 4, 6, 8, 10] 5 doubles_by_3 = [x*2 for x in range(1,6) if (x*2)%3 == 0] 6 # => [6] 7 even_squares = [x**2 for x in range(1,11) if x%2 ==0] 8 # => [4, 16, 36, 64, 100]
1 garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI" 2 message = garbled[::-2]#逆序 3 print message 4 #I am the secret message!
4、lambda
1 languages = ["HTML", "JavaScript", "Python", "Ruby"] 2 print filter(lambda x: x == ‘Python‘,languages) 3 #[‘Python‘]
等价于
1 languages = ["HTML", "JavaScript", "Python", "Ruby"] 2 def by_Py(languages): 3 lst_new = [] 4 for i in languages: 5 if i == ‘Python‘: 6 lst_new.append(i) 7 return lst_new 8 print by_Py(languages)
1 my_list = range(16) 2 print filter(lambda x: x % 3 == 0, my_list) 3 #[0, 3, 6, 9, 12, 15]
等价于
1 my_list = range(16) 2 def by_three(x): 3 lst_new = [] 4 for i in x: 5 if i%3 == 0: 6 lst_new.append(i) 7 return lst_new 8 print by_three(my_list)
1 squares = [x**2 for x in range(1,11)] 2 print filter(lambda x : 30<=x<=70,squares)
等价于
1 squares = [x**2 for x in range(1,11)] 2 def by_sq(squares): 3 lst_new = [] 4 for i in squares: 5 if 30<=i<=70: 6 lst_new.append(i) 7 return lst_new 8 print by_sq(squares)
时间: 2024-10-11 09:17:37