首页 > 代码库 > python学习笔记(3)—— dict&tuple&somthing advance
python学习笔记(3)—— dict&tuple&somthing advance
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 message4 #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_new8 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_new8 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_new8 print by_sq(squares)
python学习笔记(3)—— dict&tuple&somthing advance
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。