码迷,mamicode.com
首页 > 编程语言 > 详细

python学习笔记(3)—— dict&tuple&somthing advance

时间:2014-11-20 18:24:25      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:style   blog   ar   color   sp   java   for   on   div   

 

  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)

 

python学习笔记(3)—— dict&tuple&somthing advance

标签:style   blog   ar   color   sp   java   for   on   div   

原文地址:http://www.cnblogs.com/andrew-elec90/p/4111090.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!