【问题标题】:Python: find exact word in listPython:在列表中找到确切的单词
【发布时间】:2017-09-07 07:09:41
【问题描述】:

设置

我有以下字典,

d={'City':['Paris', 'Berlin','Rome', 'London']}

以及下面的单元素列表,

 address=['Bedford Road, London NW7']   


问题

我想检查其中一个城市是否在地址中。


目前尝试过

(1)

for x in d['City']:
  if x in address:
    print('yes')
  else: 
    print('no')

只打印no

(2)

for x in d['City']:
  r = re.compile(x)
  newlist = list(filter(r.match, address)) 

给出TypeError: 'str' object is not callable。从this answer 得到这个似乎应该解决这个问题,但错误没有帮助。

我该怎么做?

【问题讨论】:

    标签: python regex list


    【解决方案1】:

    您的解决方案 #1 实际上非常接近,但它不起作用,因为 address 是字符串列表,而不是字符串本身。

    所以,如果你只取列表address 的第一个元素,即address[0],它会很好地工作。

    或者,你可以试试这个:

    >>> any(i in address[0] for i in d['City'] )
    True
    

    对于代码sn-p,可以使用:

    if any(i in address[0] for i in d['City'] ):
        print 'Yes'
    else:
        print 'No'
    

    【讨论】:

    • 谢谢。就是这样。切换到您的光滑替代方案;)
    【解决方案2】:

    由于您的地址是单元素列表,因此您应该检查address[0] 而不是address

    for x in d['City']:
        if x in address[0]:
            print('yes')
        else:
            print('no')
    

    【讨论】:

      【解决方案3】:

      如果您不增加列表的大小:

      for x in d['City']:
          if x in address[0]:
              print('yes')
          else: 
              print('no')
      

      【讨论】:

      • 你不需要使用split,你可以去掉它,它会继续工作。
      • 要改进你的帖子,你可以改进你的解释。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      • 2021-01-24
      • 2017-01-28
      • 2022-07-06
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      相关资源
      最近更新 更多