您的位置:首页 > 编程语言 > Python开发

给PYTHON初学者的技巧

2013-11-01 22:48 381 查看
[b]原[/b]文地址:http://maxburstein.com/blog/python-shortcuts-for-the-python-beginner/

下面这些内容是我多年使用python总结出来一些有用的提示和工具,希望对读者们有些帮助。

变量交换

print "Hello" if True else "World" >>> Hello

字符串连接

最后一个是一个很酷的连接了两种不同类型的对象的方式。

 afc = ["Ravens", "Patriots"] print nfc + afc >]

数字诀窍

#Floor Division (rounds down) print 5.0//2 >>> 2  #2 raised to the 5th power print 2**5 >> 32

小心除法和浮点数!

x = 2  if 3 > x > 1: print x >>> 2  if 1 < x > 0: print x >>> 2

同时遍历两个列表

 afc = ["Ravens", "Patriots"]  for teama, teamb in zip(nfc, afc): print teama + " vs. " + teamb  >]teams = ["Packers", "49ers", "Ravens", "Patriots"] for index, team in enumerate(teams): print index, team  >>> 0 Packers >>> 1 49ers >>> 2 Ravens >>> 3 Patriots

列表解析

 even = [number for number in numbers if number%2 == 0]

字典解析

teams = ["Packers", "49ers", "Ravens", "Patriots"] print {key: value for value, key in enumerate(teams)} >]items = [0]*3 print items >>> [0,0,0]

列表转换成字符串

 print ", ".join(teams) >]data = {'user': 1, 'name': 'Max', 'three': 4} is_admin = data.get('admin', False)

列表的子集

  #First 3  print x[:3] >]from collections import Counter  print Counter("hello") >>> Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

Itertools模块

 for game in combinations(teams, 2): print game  >]False = True if False: print "Hello" else: print "World"  >>> Hello


如果你有任何其他很酷的提示/技巧,让他们在下面的意见。感谢您的阅读!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: