【问题标题】:matching strings in list against strings python将列表中的字符串与字符串python匹配
【发布时间】:2016-08-12 18:18:45
【问题描述】:

假设我有一个列表match = ['one', 'two', 'three']

我有一个参数列表foo = ['something', 'something_two', 'something', (...)]

我只想对与match 列表中的任何项目匹配的项目进行操作:

for each in foo:
    for match_item in match:
        if match_item not in each:
            no_match = True
            break
    if no_match:
        break
    # do the desired operations

但我不知道如何做到这一点,以便当'something_two' 遇到'one' 并打破所有循环时它不会失败。 match 中的项目将只是 foo 项目中整个字符串的一部分,这就是我循环遍历 match 中的项目列表的原因。

解决这个问题的好方法是什么?

【问题讨论】:

  • 你不能只做if each in match: # do desired op 吗?

标签: python-2.7 search string-matching


【解决方案1】:

我能想到的最简单的方法是

for item in foo:
    if item in match:
        # do desired operations

或者如果你想对列表本身进行操作

for i in range(len(foo)):
    if foo[i] in match:
        # do desired operation on foo[i]

【讨论】:

    【解决方案2】:

    您可以使用带有条件的生成器表达式来减少列表:

    for each in (item for item in foo if item in match):
        # do the desired operations
    

    或者使用filter函数:

    for each in filter(lambda item: item in match, foo):
        # do the desired operations
    

    【讨论】:

    • 如果item 包含的字符多于match[0] 中的字符,第一种方法是否有效?说each = 'something_one' 和匹配只有'one' 我似乎无法让它工作
    猜你喜欢
    • 2013-06-18
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2021-08-02
    • 2018-09-13
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多