python常用技巧

List遍历的三种方法

方法1:

for i in list:
    print i

方法2:

for i in range(len(list)):
     print i, list[i]

方法3:

for i in xrange(len(list)):
     print i, list[i]

方法4:

for i, j in enumerate(list):
    print i, j

dict遍历的三种方法

from time import clock

t0 = clock()
for i in d:
    t = i + d[i]
t1 = clock()

for k, v in d.items():
    t = k + v
t2 = clock()


for k,v  in zip(d.keys(),d.values()):
    t = k + v
t3 = clock()


print(t1 - t0, t2 - t1, t3 - t2)

1、原地交换两个数字

x, y =10, 20
print(x, y)
y, x = x, y
print(x, y)

10 20
20 10

2、链状比较操作符

n = 10
print(1 < n < 20)
print(1 > n <= 9)

True
False

3、使用三元操作符来实现条件赋值

y = 20
x = 9 if (y == 10) else 8
print(x)

8

# 找abc中最小的数
def small(a, b, c):
    return a if a<b and a<c else (b if b<a and b<c else c)
print(small(1, 0, 1))
print(small(1, 2, 2))
print(small(2, 2, 3))
print(small(5, 4, 3))

0
1
3
3

# 列表推导
x = [m**2 if m>10 else m**4 for m in range(50)]
print(x)

[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]

4、多行字符串

multistr = "select * from multi_row \
where row_id < 5"
print(multistr)

select * from multi_row where row_id < 5

5、存储列表元素到新的变量

testList = [1, 2, 3]
x, y, z = testList    # 变量个数应该和列表长度严格一致
print(x, y, z)

1 2 3

6、打印引入模块的绝对路径

import threading
import socket
print(threading)
print(socket)

<module ‘threading’ from ‘d:\python351\lib\threading.py’>
<module ‘socket’ from ‘d:\python351\lib\socket.py’>

8、字典/集合推导

testDic = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(10)}
print(testDic)
print(testSet)

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
{0, 2, 4, 6, 8, 10, 12, 14, 16, 18

12、简化if语句

# use following way to verify multi values
if m in [1, 2, 3, 4]:
# do not use following way
if m==1 or m==2 or m==3 or m==4:

14、组合多个字符串

test = ["I", "Like", "Python"]
print(test)
print("".join(test))
['I', 'Like', 'Python']

ILikePython

15、四种翻转字符串、列表的方式

# 翻转列表本身
testList = [1, 3, 5]
testList.reverse()
print(testList)

[5, 3, 1]

# 在一个循环中翻转并迭代输出
for element in reversed([1, 3, 5]):
    print(element)

5
3
1

# 翻转字符串
print("Test Python"[::-1])

nohtyP tseT

# 用切片翻转列表
print([1, 3, 5][::-1])

[5, 3, 1]

16、用枚举在循环中找到索引

test = [10, 20, 30]
for i, value in enumerate(test):
    print(i, ':', value)

0 : 10

1 : 20

2 : 30

17、定义枚举量

class shapes:
    circle, square, triangle, quadrangle = range(4)
print(shapes.circle)
print(shapes.square)
print(shapes.triangle)
print(shapes.quadrangle)

18、从方法中返回多个值

def x():
    return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)

1 2 3 4

19、使用*运算符unpack函数参数

def test(x, y, z):
    print(x, y, z)
testDic = {'x':1, 'y':2, 'z':3}
testList = [10, 20, 30]
test(*testDic)
test(**testDic)
test(*testList)

z x y

1 2 3

10 20 30

20、用字典来存储表达式

stdcalc = {
    "sum": lambda x, y: x + y,
    "subtract": lambda x, y: x - y
}
print(stdcalc["sum"](9, 3))
print(stdcalc["subtract"](9, 3))

12

6

27、从两个相关序列构建一个字典

t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))

{1: 10, 2: 20, 3: 30}

28、搜索字符串的多个前后缀

print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))

33、查找列表中某个元素的下标

>>>a = ["a","b","c","d","e","f"]
>>>a.index("b")
>>> 1

34、包管理

Python世界最棒的地方之一,就是大量的第三方程序包。同样,管理这些包也非常容易。按照惯例,会在 requirements.txt 文件中列出项目所需要的包。每个包占一行,通常还包含版本号。

pelican==3.3
Markdown
pelican-extended-sitemap==1.0.0

36、 隐藏特性 — print 重定向输出到文件注意打开的模式:

“w+” 而不能 “w” , 当然 “a” 是可以的

 >>> print >> open("somefile", "w+")

37、隐藏特性 — isinstance可以接收一个元组

这个真的鲜为人知, 我们可以用 isinstance(x, (float, int)) 来判断 x 是不是数,也就是那个元组里面是 或 的关系,只要是其中一个的实例就返回 True。

>>> isinstance(1, (float, int))

True

>>> isinstance(1.3, (float, int))

True

>>> isinstance("1.3", (float, int))

False

38 调用函数时使用* **

test(args) 的作用其实就是把序列 args 中的每个元素,当作位置参数传进去。比如上面这个代码,如果 args 等于 (1,2,3) ,那么这个代码就等价于 test(1, 2, 3) 。

test(kwargs) 的作用则是把字典 kwargs 变成关键字参数传递。比如上面这个代码,如果 kwargs 等于 {‘a’:1,‘b’:2,‘c’:3} ,那这个代码就等价于 test(a=1,b=2,c=3) 。

39 定义函数参数时使用* **

def test(*args):

…定义函数参数时 * 的含义又要有所不同,在这里 *args 表示把传进来的位置参数都装在元组 args 里面。比如说上面这个函数,调用 test(1, 2, 3) 的话, args 的值就是 (1, 2, 3) 。:

def test(**kwargs):

…类似的, ** 就是针对关键字参数和字典的了。 调用 test(a=1,b=2,c=3) 的话, kwargs 的值就是 {‘a’:1,‘b’:2,‘c’:3} 了。

普通的参数定义和传递方式和 * 们都可以和平共处,不过显然 * 必须放在所有位置参数的最后,而 ** 则必须放在所有关键字参数的最后,否则就要产生歧义了

40.导出当期环境

导出命令为:pip freeze > filename.txt,其中filename可以自己定义。
在新环境下安装移植项目依赖的三方库方法为pip install -r filename.txt
笔者在共享服务器上无root权限的安装放那方法
pip install --user -I <package_name>

41.根据str调用函数

def parse_func(func, predefined):
    if callable(func):
        return func
    if func is None:
        return lambda x: x
    else:
        return predefined[func]
preprocessor_map = {
    "landmark_18p_mat": functools.partial(preprocessor, lmk_type="18p"),
    "landmark_81p_mat": functools.partial(preprocessor, lmk_type="81p"),
    "landmark_18p_idx": std_preprocessor,
    "preproc_ag_rc": functools.partial(preprocessor, lmk_type="81p", lmk_flatten=False, matrix=False),
    "preproc_pb1118": preproc_pb1118,
    "resize_transpose": resize_transpose,
    "frvt_release_preprocessor": frvt_release_preprocessor,
}
self._preproc = parse_func(preprocessor, preprocessor_map)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值