[['Demo-Site', '10.227.209.139'], ['Demo-Site', '10.227.215.68'],
['Demo-Site', '172.18.74.146'], ['Site', '10.152.114.65'],
['Site', '10.227.211.244'], ['Demo-Site', '10.227.147.98'],
['test', '172.18.74.146']]
如何根据第一个索引是否相同将所有 IP 连接起来形成一个大字符串?我要制作默认词典吗?
应该是:
["Site", "10.227.211.244, 10.152.114.65"]
最佳答案
这里,使用基于 defaultdict
的解决方案:
In [1]: list_of_ips = [['Demo-Site', '10.227.209.139'], ['Demo-Site', '10.227.215.68'],
...: ['Demo-Site', '172.18.74.146'], ['test', '10.152.114.65'],
...: ['Site', '10.227.211.244'], ['Demo-Site', '10.227.147.98'],
...: ['test', '172.18.74.146']]
In [2]: from collections import defaultdict
In [3]: resp_dict = defaultdict(list)
In [4]: for item in list_of_ips:
...: resp_dict[item[0]].append(item[1])
...:
In [5]: result = [[key, ", ".join(resp_dict[key])] for key in resp_dict]
In [6]: result
Out[6]:
[['test', '10.152.114.65, 172.18.74.146'],
['Site', '10.227.211.244'],
['Demo-Site', '10.227.209.139, 10.227.215.68, 172.18.74.146, 10.227.147.98']]
关于python - 在Python中从列表构建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32018520/