python小技巧集锦

1.安装autopep8工具可以将代码规范化

指令

autopep8 --in-place --aggressive --aggressive demo.py
2. 共享文件

在某一文件下执行

python -m http.server

在浏览器中输入'xxx.xxx.xxx.xxx.8000' 即可查看、下载该文件夹下文件

3. 字典排序(根据key或者value)
word_list_order = sorted(word_dict.items(), key = lambda e:e[0], reverse = True) ##根据key降序
word_list_order = sorted(word_dict.items(), key = lambda e:e[1], reverse = True) ##根据value 降序

word_dict = { item[0]:item[1] for item in word_list_order}    ## 恢复为字典
4. 通过dict实现switch语句
def calc(operator, x, y):
    operator_dict = {
        '+': x + y,
        '-': x - y,
        '*': x * y,
        '/': x / y,
    }

    result = operator_dict.get(operator, None)
    if result is None:
        return 'invalid operator'
    else:
        return result

print (calc('+', 2, 1))
5. 判断序列是否为空

如果通过len()函数判断序列是否为空,当序列为空时,则会抛出异常
推荐:

if A:  ## 序列非空
    pass: