2012-09-27 62 views
1

我读了一个文件并用关键字对它进行分组。我也有一个列表,如果列表中的值在组中,我该如何检查它?不只检查一个条目,检查列表中的所有条目。组中的python列表值

示例但未对照组检查列表。我不想写任何或任何blabla。

hosts = ['blabla.dyndns.org','blabla1.dyndns.org'] 
    with open(testfile,'r') as f: 
     for key,group in it.groupby(f,lambda line: line.startswith('[hosts]')): 
      if not key: 
       group = list(group) 
       if any("blabla.dyndns.org" in s for s in group) or any("blabla.dyndns.org" in s for s in group): 
        print 'yes' 
       else: 
        print 'no' 

谢谢,问候。


我想脚本,我可以在例如更改某些主机的协议。

import itertools as it 
testfile='blabla.txt' 

hosts = set(['blabla.dyndns.org','blabla1.dyndns.org']) 

with open(testfile,'r') as f: 
    for key,group in it.groupby(f,lambda line: line.startswith('[host]')): 
     if not key: 
      group = set(group) 
      if group & hosts: # set intersection 
       print '[host]\n' 
       for (i, item) in enumerate(group): 
        if 'protocol' in item: 
         group[i] = 'protocol  = udp\n' 
       j = ', '.join(group) 
       y = j.replace(", ", "") 
       print y 
      else: 
       print '[host]\n' 
       j = ', '.join(group) 
       y = j.replace(", ", "") 
       print y 

exit(0) 

不起作用。

回答

2

使用设置路口:

hosts = set(['blabla.dyndns.org','blabla1.dyndns.org']) 
with open(testfile,'r') as f: 
    for key,group in it.groupby(f,lambda line: line.startswith('[hosts]')): 
     if not key: 
      group = set(group) 
      if group & hosts: # set intersection 
       print 'yes' 
      else: 
       print 'no' 
+0

集不能被使用,因为文件,我读有许多[主持人]协议[主持人]协议等。设置消除了像协议这样的重复。 – user1701820

+0

但是你正在使用'groupby' ... – nneonneo