一行式

python 以简洁易懂著称,往往一行代码可以顶其它语言大段语块,本文收录了大部分这种常用神操作

  • 简易Web Server

    # Python 2
    python -m SimpleHTTPServer
    
    # Python 3
    python -m http.server
  • 美化打印

    from pprint import pprint
    
    my_dict = {'name': 'Yasoob', 'age': 'undefined', 'personality': 'awesome'}
    pprint(my_dict)
  • 打印json文件

    cat file.json | python -m json.tool
  • 性能分析

    python -m cProfile my_script.py
  • csv 转json

    python -c "import csv,json;print json.dumps(list(csv.reader(open('csv_file.csv'))))"
  • 列表碾平

    a_list = [[1, 2], [3, 4], [5, 6]]
    print(list(itertools.chain.from_iterable(a_list)))
    # Output: [1, 2, 3, 4, 5, 6]
    
    # or
    print(list(itertools.chain(*a_list)))
    # Output: [1, 2, 3, 4, 5, 6]
  • 批量初始化

    class A(object):
        def __init__(self, a, b, c, d, e, f):
            self.__dict__.update({k: v for k, v in locals().items() if k != 'self'})
  • 推导式

    
    # 字典推导
    {v: k for k, v in some_dict.items()}
    # 集合推导
    {x**2 for x in [1, 1, 2]}
    # 列表推导
    [i for i in range(30) if i % 3 is 0]
本作品采用《CC 协议》,转载必须注明作者和本文链接
pardon110
讨论数量: 2
>>> a_list = [[1, 2], [3, 4], [5, 6]]
>>> sum(a_list,[])
[1, 2, 3, 4, 5, 6]
4年前 评论
Jason990420

列表碾平

>>> a_list = [[1, 2], 7, [3, [5, 6, 7], 4], [5, 6]]
>>> print(list(itertools.chain.from_iterable(a_list)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> print(list(itertools.chain(*a_list)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
3年前 评论
pardon110 (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
开发者 @ 社科大
文章
134
粉丝
24
喜欢
101
收藏
55
排名:106
访问:8.9 万
私信
所有博文
社区赞助商