zoukankan      html  css  js  c++  java
  • Python高效编程技巧

    1.控制台输出格式化的json数据

    使用python内置的json处理,可以使JSON串具有一定的可读性,但当遇到大型数据时,它表现成一个很长的、连续的一行时,人的肉眼就很难观看了。为了能让JSON数据表现的更友好,我们可以使用indent参数来输出漂亮的JSON。当在控制台交互式编程或做日志时,这尤其有用:

     1 >>> import json
     2 >>> data = {"status": "OK", "count": 2, "results": [{"age": 27, "name": "Oz", "lactose_intolerant": 'true'}, {"age": 29, "name": "Joe", "lactose_intolerant": 'false'}]}
     3 >>> print(json.dumps(data))  # No indention
     4 {"status": "OK", "count": 2, "results": [{"age": 27, "name": "Oz", "lactose_intolerant": 'true'}, {"age": 29, "name": "Joe", "lactose_intolerant": 'false'}]}
     5 
     6 >>> print(json.dumps(data, indent=2))  # With indention
     7 {
     8     "status": "OK",
     9     "count": 2,
    10     "results": [
    11         {
    12             "age": 27,
    13             "name": "Oz",
    14             "lactose_intolerant": true
    15         },
    16         {
    17             "age": 29,
    18             "name": "Joe",
    19             "lactose_intolerant": false
    20         }
    21     ]
    22 }

    2.同时迭代两个列表

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

    3.带索引的列表迭代

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

    4.列表转换成字符串

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

    5.查找元素中的所有组合

    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')
  • 相关阅读:
    事务
    约束条件(CONSTRAINTS)
    算术运算符
    数据查询、修改指令
    iview-admin使用webpack打包之后发布报Uncaught SyntaxError: Unexpected token <
    使用localhost可以访问,但使用本地ip+端口号无法访问
    datatables里面的search怎么去掉?
    删除操作之后的确定或取消弹出框?
    jquery实现上传图片本地预览效果
    怎么改变title属性的样式?
  • 原文地址:https://www.cnblogs.com/sanduzxcvbnm/p/10449023.html
Copyright © 2011-2022 走看看