组中的python列表值

时间:2012-09-27 00:12:50

标签: python list

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

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

不起作用。

1 个答案:

答案 0 :(得分:2)

使用set intersection:

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'