代码之家  ›  专栏  ›  技术社区  ›  Buddy Bob Youngkhaf

比较忽略某些字符的单词-Python

  •  -1
  • Buddy Bob Youngkhaf  · 技术社区  · 5 年前

    我见过几个类似的问题,但在python中没有。基本上,我想检查某些单词是否在列表中。虽然我想比较的词可能有一个','我想忽略。我试过这个,虽然它没有忽略','。

    x = ['hello','there,','person']
    y = ['there','person']
    similar = [words for words in x if words in y ]
    print(similar)
    
    

    ['person']
    

    但我想

    ['there','person']
    

    有人知道最简单的实现方法吗?

    2 回复  |  直到 5 年前
        1
  •  6
  •   Davinder Singh    5 年前

    查看此代码使用 any function map 绘制包含条件的地图。

    x = ['hello','there,','person']
    y = ['there','person'] # or take this for more intuation ['there','person','bro']
    similar = [words for words in y if any(map(lambda i: i.count(words), x))]
    print(similar)
    

    输出:

    ['there', 'person']
    
        2
  •  1
  •   ThePyGuy Tim Roberts    5 年前

    只需比较不带逗号的字符串:

    similar = [words for words in x if words.replace(',', '') in y ]
    

    输出

    >>similar
    ['there,', 'person']