[英]Separating Lists Based on string match - Python
I have a list as below 我有一个清单如下
hostlist = ['hosta', 'Linux', 'hostb', 'Windows', 'hostc', 'Windows', 'hostd', 'Linux']
Want to create two lists based on OStype 要基于OStype创建两个列表
winlist = ['hostb','hostc']
unixlist = ['hosta','hostd']
Any ideas? 有任何想法吗?
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)
You can use list-comprehensions
: 您可以使用
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']
There are several ways to solve it. 有几种解决方法。 Assuming that the name always has OSType next to it, the simple iterative way is to go through the list
假设名称旁边总是有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
You can use a defaultdict to easily create a dictionary of all OSes: 您可以使用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())
You can try something like this: 您可以尝试如下操作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.