参考:https://www.quora.com/Python-programming-language-1/What-are-some-cool-Python-tricks
1.几个简单的
产生一个数组
[10 * x for x in a]
产生一个迭代(a generatorexpression)
(10 * x for x in a)
dict和set
>>> {x: 10 * x for x in range(5)}
{0: 0, 1: 10, 2: 20, 3: 30, 4: 40}
>>> {10 * x for x in range(5)}
set([0, 40, 10, 20, 30])
2.最快的速度将本地文件共享到网上
python -m SimpleHTTPServer
3.文件中最长的一行
max(open('test.txt'), key=len)
4.无穷大和无穷小
float('Inf')
float('-Inf')
5.比大小
3 > x == 1
-> False
6.循环中找index
mylist = [4,2,42]
for i, value in enumerate(mylist):
print i, ': ', value
-> 0: 4
-> 1: 2
-> 2: 42
7.'*'的用途
def foo(a, b, c):
print a, b, c
mydict = {'a':1, 'b':2, 'c':3}
mylist = [10, 20, 30]
foo(*mydict)
-> a, b, c
foo(**mydict)
-> 1, 2, 3
foo(*mylist)
-> 10 20 30
a,*b ="python
-> a='p' b=('y','t','h','o','n')
8.简单枚举
class PlayerRanking:
Bolt, Green, Johnson, Mom = range(4)
PlayerRanking.Mom
-> 4
9.交换两个数值
b, a = a, b
10.翻转数组和字符串
"Hello world"[::-1]
[1,2,3][::-1]
[1,2,3].reverse()
11.自动关闭文件流
with open("my_file.txt") as f:
print(f.readlines())
在这两句代码执行后,文件被自动关闭。