【问题标题】:In a list of items, keep first item and remove the rest that match a pattern (using python)在项目列表中,保留第一项并删除与模式匹配的其余项目(使用 python)
【发布时间】:2013-07-30 22:39:35
【问题描述】:
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%']

【问题讨论】:

    标签: python pattern-matching


    【解决方案1】:

    这样好吗?

    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%']
    

    【讨论】:

    • 有没有办法不用startswith?如果第一项是“A.Scott 83% top”怎么办?代码会失败。
    • @koogee 如果你想做一个“包含”检查,你可以做if p in item:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多