我使用 python,我正在制作一个读取字符串的函数,根据每行的第一个单词执行不同的函数,我做了类似的东西,但它什么也没做:
conf_list='''
host / yes / 7200
network / yes / 6000
applications / no / 6500
'''
list_conf={}
k=0
for line in conf_list.splitlines():
list_conf[k]=line
#print(list_conf[k])
if list_conf[0] == 'host':
print(list_conf[1], list_conf[2]) #output i wanted: yes 7200
elif list_conf[0] == 'network':
print(list_conf[1], list_conf[2]) #output: yes 6000
elif list_conf[0] == 'applications':
print(list_conf[1], list_conf[2]) #output: no 6500
也许这些if和elif不好?
请您参考如下方法:
目前还不清楚您实际上想在这里做什么。您正在创建一个字典,以一个始终为 0 的整数作为键,用每一行一遍又一遍地替换该键的值,然后访问该值并将其与您要匹配的字符串进行比较。这没有任何用处。
我认为你想要的是这个:
list_confs = {}
for line in conf_list.splitlines():
thingy, yesno, number = line.split(' / ')
list_confs[thingy] = (thingy, yesno, number)
现在您已经有了一个将每个事物映射到一组值的字典。例如,'host' 映射到三个值 'host'、'yes'、'7200'。所以,你可以这样做:
list_conf = list_confs['host']
print(list_conf[1], list_conf[2]) # will print yes 7200
