简体   繁体   English

Concat每4个字符串列表?

[英]Concat every 4 strings from a list?

I have this list: 我有这个清单:

['192', '168', '0', '1', '80', '192', '168', '0', '2', '8080']...

And i want to get this list: 我想得到这个清单:

['192.168.0.1:80', '192.168.0.2:8080']...

What is the best way of doing it ? 这样做的最佳方式是什么?

using range with list pop ? 使用rangelist弹出?

using list slicing ? 使用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']

Using starmap 使用starmap

>>> from itertools import starmap
>>> list(starmap('{}.{}.{}.{}:{}'.format,zip(*[iter(data)]*5)))
['192.168.0.1:80', '192.168.0.2:8080']

This is one way to do it, which may or may not be the "best" way: 这是一种方法,可能是也可能不是“最好的”方式:

>>> 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM