简体   繁体   中英

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 ?

using list slicing ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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