我想输入一个输入字符串,例如
"server1:port1,server2:port2,server3:port3"
并将其拆分为2个列表:
servers = [ server1, server2, server3 ]
ports = [ port1, port2, port3 ]
这里有两个分隔符:首先是"",",然后元素本身被"分开:"。
有快速的方法吗?
另外,如何" toString"任何类似的列表 portString ="端口1,端口2,端口3" ?
答案 0 :(得分:1)
使用list comprehension和join
函数来实现这一目标。
>>> a ="server1:port1,server2:port2,server3:port3"
>>> temp = [i.split(':') for i in a.split(',')]
>>> temp
[['server1', 'port1'], ['server2', 'port2'], ['server3', 'port3']]
>>> servers = [i[0] for i in temp]
>>> ports = [i[1] for i in temp]
>>> servers
['server1', 'server2', 'server3']
>>> ports
['port1', 'port2', 'port3']
>> ','.join(ports)
port1,port2,port3
答案 1 :(得分:1)
如果您想在jinja模板中执行此操作,则可以使用以下代码。
{% set server = [] %}
{% set port = [] %}
{% set x= "server1:port1,server2:port2,server3:port3" %}
{% for i in x.split(',') %}
{% for j in i.split(':') %}
{% set server = server + j[0] %}
{% set port = port + j[1] %}
{% endfor %}
{% endfor %}
但是在模板中执行此操作是一个非常糟糕的主意。如果将它作为字典传递给模板然后像这样使用它
,那就更好了{% for k,v in x.iteritems() %}
#use k as server and v as port
答案 2 :(得分:0)
实现所需输出的另一种方法:
def denormalize_addr_str(addr_str):
return reduce(lambda denorm_list, addr: denorm_list + addr.split(':'), addr_str.split(','), [])
addr_str = "server1:port1,server2:port2,server3:port3"
denorm_addr_str = denormalize_addr_str(addr_str)
servers = denorm_addr_str[::2]
ports = denorm_addr_str[::-2]
port_string = ','.join(ports)