基于字符串匹配分隔列表 - Python

时间:2018-01-25 20:12:01

标签: python list loops

我有一个列表如下

hostlist = ['hosta', 'Linux', 'hostb', 'Windows', 'hostc', 'Windows', 'hostd', 'Linux']

想要根据OStype

创建两个列表
winlist = ['hostb','hostc']

unixlist = ['hosta','hostd']

有什么想法吗?

5 个答案:

答案 0 :(得分:1)

for host_name, operating_system in zip(hostlist[:-1:2], hostlist[1::2]):
    if operating_system == 'Linux':
        unixlist.append(host_name)
    elif operating_system == 'Windows':
        winlist.append(host_name)

答案 1 :(得分:1)

您可以使用list-comprehensions

>>> winlist = [hostlist[i] for i in range(0, len(hostlist), 2) if hostlist[i+1] == 'Windows']
>>> unixlist = [hostlist[i] for i in range(0, len(hostlist), 2) if hostlist[i+1] == 'Linux']
>>> winlist
['hostb', 'hostc']
>>> unixlist
['hosta', 'hostd']

答案 2 :(得分:0)

有几种方法可以解决它。假设名称旁边总是有OSType,简单的迭代方式是遍历列表

hostlist = ['hosta', 'Linux', 'hostb', 'Windows', 'hostc', 'Windows', 'hostd', 'Linux']

winList = []
unixList = []
temp = ''

for i in hostlist:
    if i is 'Linux':
      unixList.append(temp)
    elif i is 'Windows':
      winList.append(temp)
    else:
      temp = i

答案 3 :(得分:0)

您可以使用defaultdict轻松创建所有操作系统的字典:

from collections import defaultdict
os_dict = defaultdict(list)
for host, os in zip(hostlist[::2], hostlist[1::2]):
    os_dict[os].append(host)
print(os_dict.items())

答案 4 :(得分:0)

您可以尝试这样的事情:

hostlist = ['hosta', 'Linux', 'hostb', 'Windows', 'hostc', 'Windows', 'hostd', 'Linux']

winlist=[]
unixlist=[]

for j,i in enumerate(hostlist):
    if i=='Linux' or i=='Windows':
        try:
            if i=='Linux':
                unixlist.append(hostlist[j-1])
            else:
                winlist.append(hostlist[j-1])
        except IndexError:
            pass