我有这个清单:
['192', '168', '0', '1', '80', '192', '168', '0', '2', '8080']...
我想得到这个列表:
['192.168.0.1:80', '192.168.0.2:8080']...
最好的方法是什么?
range
与list
流行音乐一起使用?
使用list
切片?
>>> data = ['192', '168', '0', '1', '80', '192', '168', '0', '2', '8080']
>>> ['{}.{}.{}.{}:{}'.format(*x) for x in zip(*[iter(data)]*5)]
['192.168.0.1:80', '192.168.0.2:8080']
使用starmap
>>> from itertools import starmap
>>> list(starmap('{}.{}.{}.{}:{}'.format,zip(*[iter(data)]*5)))
['192.168.0.1:80', '192.168.0.2:8080']
这是一种方法,它可能是也可能不是“最好”的方法:
>>> a = ['192', '168', '0', '1', '80', '192', '168', '0', '2', '8080']
>>> [":".join([".".join(a[x:x+4]), a[x+4]]) for x in range(0, len(a), 5)]
['192.168.0.1:80', '192.168.0.2:8080']