我编写python代码,并获得如下列表:
['221.180.147.30', '86', '61.155.169.11', '808']
我怎样才能把它变成:
['221.180.147.30:86', '61.155.169.11:808']
答案 0 :(得分:1)
使用列表理解:
>>> lst = ['221.180.147.30', '86', '61.155.169.11', '808']
>>> [':'.join(lst[i:i+2]) for i in range(0, len(lst), 2)]
['221.180.147.30:86', '61.155.169.11:808']
使用itertools
recipe - grouper
中引入的zip(*[iter(lst)*N]
技巧(这适用于任何可迭代的,不仅适用于列表):
>>> [':'.join(group) for group in zip(*[iter(lst)]*2)]
['221.180.147.30:86', '61.155.169.11:808']
<强>更新强>
使用map
:
>>> map(':'.join, zip(lst[::2], lst[1::2])) # In Python 2.x
['221.180.147.30:86', '61.155.169.11:808']
>>> list(map(':'.join, zip(lst[::2], lst[1::2]))) # In Python 3.x
['221.180.147.30:86', '61.155.169.11:808']
zip(lst[::2], lst[1::2])
来自Burhan Khalid的回答。
答案 1 :(得分:1)
如果zip(*[iter(lst)]*2)
导致头部过多,请尝试使用切片语法的更简单选项:
>>> ['{}:{}'.format(a,b) for a,b in zip(i[::2], i[1::2])]
['221.180.147.30:86', '61.155.169.11:808']
这是如何工作的[::2]
将跳过列表跳过一个项目,[1::2]
执行相同操作,但跳过第一个项目。实际上,[::2]
表示“奇数位置的所有条目”和[1::2]
是“偶数位置的所有条目”:
>>> i
['221.180.147.30', '86', '61.155.169.11', '808']
>>> i[::2]
['221.180.147.30', '61.155.169.11']
>>> i[1::2]
['86', '808']
zip
只是将两者结合起来,将“对”作为元组:
>>> zip(i[::2], i[1::2])
[('221.180.147.30', '86'), ('61.155.169.11', '808')]
接下来由您来决定将这些元组转换为字符串。 @falsetru用':'.join(pair)
做了它,在我的例子中,我使用的是字符串格式。有几种方法可以做到这一点:
>>> ['{}:{}'.format(*pair) for pair in zip(i[::2], i[1::2])]
['221.180.147.30:86', '61.155.169.11:808']
>>> [':'.join(pair) for pair in zip(i[::2], i[1::2])]
['221.180.147.30:86', '61.155.169.11:808']
>>> ['{}:{}'.format(ip, port) for ip, port in zip(i[::2], i[1::2])]
['221.180.147.30:86', '61.155.169.11:808']
我们都使用 list comprehension ,这是一个评估为列表的表达式。
答案 2 :(得分:0)
可能更简洁......
>>> l = ['221.180.147.30', '86', '61.155.169.11', '808']
>>> [':'.join(s) for s in zip(l[::2], l[1::2])]
['221.180.147.30:86', '61.155.169.11:808']
由于套接字是源IP,源端口,目标IP,目标端口和协议的元组,因此也可以认为它接近于套接字的理论类型。
看起来有几个人想出了同样的答案。
答案 3 :(得分:-1)
>>> li=['221.180.147.30', '86', '61.155.169.11', '808']
>>> [':'.join(t) for t in zip(li[0::2], li[1::2])]
['221.180.147.30:86', '61.155.169.11:808']