1

我读取一个文件并按关键字对其进行分组。我还有一个列表,如果列表中的值在组中,我如何检查它?不只检查一个条目,而是对照组检查列表中的所有条目。

示例但未针对组检查列表。我不想写任何或任何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)

不工作。

4

1 回答 1

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'
于 2012-09-27T00:16:24.050 回答