在项目列表中,保留第一个项目并删除与模式匹配的其余项目(使用python)

时间:2013-07-30 22:39:36

标签: python pattern-matching

list = ['Scott 83% top', 'Tony 22%', 'Tony B 12% failed', 'James 66%', 'James Lipton 9%', 'Adams 76% excellent', 'Scott Brown 53%']    
pattern = ['Scott', 'Tony', 'James']

我希望结果是:

['Scott 83% top', 'Tony 22%', 'James 66%']

1 个答案:

答案 0 :(得分:2)

这可以吗?

In [1]: list = ['Scott 83% top', 'Tony 22%', 'Tony B 12% failed', 'James 66%', 'James Lipton 9%', 'Adams 76% excellent', 'Scott Brown 53%']

In [2]: pattern = ['Scott', 'Tony', 'James']    

In [3]: l=[]

In [4]: for item in list:                                                                                                                                                   
   ...:     for p in pattern:
   ...:         if item.startswith(p):
   ...:             l.append(item)
   ...:             pattern.remove(p)
   ...:             break
   ...:             

In [5]: l
Out[5]: ['Scott 83% top', 'Tony 22%', 'James 66%']