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')

 

posted @ 2019-02-28 11:02  哈喽哈喽111111  阅读(378)  评论(0编辑  收藏  举报