【问题标题】:How to find string in item of list python如何在列表python的项目中查找字符串
【发布时间】:2015-10-05 22:46:18
【问题描述】:

我需要你的帮助,因为我想在列表中找到一个 str 以获得完整的项目。

my_list: 看起来像:

['Mont Saint Martin, 42 rue de Bordeaux', 'Mont de Marsan, 100 avenue Pierre de Coubertin', 'Lyon, 56 rue du Docteur Alb\xc3\xa9ric Pont', 'Lille, 90 rue d\xe2\x80\x99Arras', 'Lyon, 2 all\xc3\xa9e des fleurs']

str: 看起来像:

“圣”或“德”

处理后的预期列表我想在','之前检查:

['Mont Saint Martin']

or for str = "de"

['Mont de Marsan']

我已经尝试过:

new = filter(lambda x: x.my_list == str, x)[0]

感谢您的帮助。

【问题讨论】:

  • 我投票结束这个问题作为题外话,因为 SO 不是代码编写服务
  • 我已经尝试了 new = filter(lambda x: x.my_list == str, x)[0]
  • @TheFirstLoop "de" 也将匹配 Mont Saint Martin, 42 rue de Bordeaux 如果使用 in 你想要吗
  • @TheFirstLoop 请使用您尝试过的代码(完整代码,包括正则表达式定义)以及出了什么问题来编辑您的帖子。
  • 顺便说一句,不要使用 str 作为变量名,因为这会“遮蔽”内置的 str 函数。这意味着如果您稍后尝试使用 str 函数,Python 会认为您的意思是 str 变量,您的程序可能会崩溃。

标签: python list search split find


【解决方案1】:
cities = [w.split(',')[0] for w in my_list]
term = "de"
results = [city for city in cities if term in city.lower()]

【讨论】:

    【解决方案2】:

    使用re.match 函数。

    >>> l = ['Mont Saint Martin, 42 rue de Bordeaux', 'Mont de Marsan, 100 avenue Pierre de Coubertin', 'Lyon, 56 rue du Docteur Alb\xc3\xa9ric Pont', 'Lille, 90 rue d\xe2\x80\x99Arras', 'Lyon, 2 all\xc3\xa9e des fleurs']
    >>> st = ["saint","de"]
    >>> for i in st:
            for j in l:
                for x in j.split(','):
                    if re.match(r'(?i)\S+ ' + i + r' \S+$', x):
                        print(x)
    
    
    Mont Saint Martin
    Mont de Marsan
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      • 2021-10-26
      • 2015-08-03
      • 2023-03-27
      • 2023-04-03
      • 2011-08-31
      相关资源
      最近更新 更多