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