给Python初学者的技巧

原文地址:http://maxburstein.com/blog/python-shortcuts-for-the-python-beginner/



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


变量交换

x = 6
y = 5
 
x, y = y, x
 
print x
>>> 5
print y
>>> 6

单行的if声明

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

字符串连接

最后一个是一个很酷的连接了两种不同类型的对象的方式。
nfc = ["Packers", "49ers"]
afc = ["Ravens", "Patriots"]
print nfc + afc
>>> ['Packers', '49ers', 'Ravens', 'Patriots']
 
print str(1) + " world"
>>> 1 world
 
print `1` + " world"
>>> 1 world
 
print 1, "world"
>>> 1 world
print nfc, 1
>>> ['Packers', '49ers'] 1

数字诀窍

#Floor Division (rounds down)
print 5.0//2
>>> 2
 
#2 raised to the 5th power
print 2**5
>> 32
小心除法和浮点数!
print .3/.1
>>> 2.9999999999999996
 
print .3//.1
>>> 2.0

数值比较

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

同时遍历两个列表

nfc = ["Packers", "49ers"]
afc = ["Ravens", "Patriots"]
 
for teama, teamb in zip(nfc, afc):
    print teama + " vs. " + teamb
 
>>> Packers vs. Ravens
>>> 49ers vs. Patriots

遍历列表同时得出序号和内容

teams = ["Packers", "49ers", "Ravens", "Patriots"]
for index, team in enumerate(teams):
    print index, team
 
>>> 0 Packers
>>> 1 49ers
>>> 2 Ravens
>>> 3 Patriots

列表解析

numbers = [1,2,3,4,5,6]
even = [number for number in numbers if number%2 == 0]

字典解析

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

初始列表值

items = [0]*3
print items
>>> [0,0,0]

列表转换成字符串

teams = ["Packers", "49ers", "Ravens", "Patriots"]
print ", ".join(teams)
>>> 'Packers, 49ers, Ravens, Patriots'

从字典中获得值(key)

data = {'user': 1, 'name': 'Max', 'three': 4}
is_admin = data.get('admin', False)

列表的子集

x = [1,2,3,4,5,6]
 
#First 3 
print x[:3]
>>> [1,2,3]
 
#Middle 4
print x[1:5]
>>> [2,3,4,5]
 
#Last 3
print x[-3:]
>>> [4,5,6]
 
#Odd numbers
print x[::2]
>>> [1,3,5]
 
#Even numbers
print x[1::2]
>>> [2,4,6]

Collections模块

除了Python的内置数据类型,在collections模块中提供了一些额外的特殊用途。我发现计数器有时是非常有用的。你甚至可以找到一些有用的,如果你参与了今年Facebook的HackerCup。
from collections import Counter
 
print Counter("hello")
>>> Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

Itertools模块

from itertools import combinations
 
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for game in combinations(teams, 2):
    print game
 
>>> ('Packers', '49ers')
>>> ('Packers', 'Ravens')
>>> ('Packers', 'Patriots')
>>> ('49ers', 'Ravens')
>>> ('49ers', 'Patriots')
>>> ('Ravens', 'Patriots')

False == True

这是一个有趣的一个比一个有用的技术。在Python中True和False是基本上是全局变量。因此:
False = True
if False:
    print "Hello"
else:
    print "World"
 
>>> Hello

如果你有任何其他很酷的提示/技巧,让他们在下面的意见。感谢您的阅读!