首页 > 编程语言 > 详细

Python高效编程技巧

时间:2019-02-28 11:52:11      阅读:152      评论:0      收藏:0      [点我收藏+]

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)

 

Python高效编程技巧

原文:https://www.cnblogs.com/sanduzxcvbnm/p/10449023.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!