(
(1, '10.121.1.1:4730'),
(2, '127.0.0.1:4730'),
(3, '127.0.0.1:4730')
)
如何格式化为以下格式 用python
{
'10.121.1.1:4730':
[(1, '10.121.1.1:4730')],
'127.0.0.1:4730':
[(2, '127.0.0.1:4730'), (3, '127.0.0.1:4730')]
}
高洛峰2017-04-17 17:55:37
根据@dokelung,@松林两位老兄提供的建议改进
ips = (
(1, '10.121.1.1:4730'),
(2, '127.0.0.1:4730'),
(3, '127.0.0.1:4730')
)
dic = {}
for v, k in ips:
dic.setdefault(k, []).append((v, k))
print dic
PHP中文网2017-04-17 17:55:37
虽然已经有采纳了,但还是可以提下:
看到这个setdefault,就想起collections.defaultdict,功能比setdefault更强大,接受的参数可以使默认初始化类型,也可以是函数。其实也可以更简洁
from collections import defaultdict
ips = (
(1, '10.121.1.1:4730'),
(2, '127.0.0.1:4730'),
(3, '127.0.0.1:4730')
)
result = defaultdict(list)
for v, k in ips:
result[k].append((v, k))
天蓬老师2017-04-17 17:55:37
上面的是数组,下面的是dict()序列号后的JSON。把数组遍历然后拼接成字典,输出JSON即可。
import json
a = (
(1, '10.121.1.1:4730'),
(2, '127.0.0.1:4730'),
(3, '127.0.0.1:4730')
)
b = dict()
for value in a :
number = value[0]
address = value[1]
if address not in b :
b[address] = []
b[address].append([number, address])
print json.dumps(b)