在python中比较和过滤列表元素

kar*_*nai 0 python python-2.7

我正在寻找过滤列表中的元素.

比方说,我有一个清单:

listA = ['banana', 'apple', 'appleRed', 'melon_01', 'appleGreen', 'Orange', 'melon_03']
listB = ['apple', 'melon']
Run Code Online (Sandbox Code Playgroud)

现在我需要比较列表并生成一个列表,其中只包含以listB开头的元素名称.

结果应该是:

listResult = ['apple', 'appleRed', 'melon_01', 'appleGreen', 'melon_03']
Run Code Online (Sandbox Code Playgroud)

我可以在2 for循环中使用if循环比较.喜欢,

for item in listA:
    for fruit in listB:
        if item.startswith(fruit):
            listResult.append(item)
            break
Run Code Online (Sandbox Code Playgroud)

但是,我想知道是否有任何捷径可用于此操作,因为这可能需要更多时间进行大列表比较.

Ste*_*noP 5

使用列表推导和any生成器:

[item for item in listA if any(item.startswith(fruit) for fruit in listB)]
Run Code Online (Sandbox Code Playgroud)

或者,正如@DSM正确建议的那样:

[item for item in listA if item.startswith(tuple(listB))]
Run Code Online (Sandbox Code Playgroud)

这比第一个解决方案更快,几乎与@Iguananaut提出的正则表达式解决方案一样快(但更紧凑和可读):

In [1]: %timeit [item for item in listA if any(item.startswith(fruit) for fruit in listB)]
100000 loops, best of 3: 4.31 us per loop

In [2]: %timeit [item for item in listA if item.startswith(tuple(listB))]
1000000 loops, best of 3: 1.56 us per loop

In [3]: %timeit filter(regex.match, listA)
1000000 loops, best of 3: 1.39 us per loop
Run Code Online (Sandbox Code Playgroud)

  • `.startswith`也接受一个字符串元组作为参数,所以`if item.startswith(tuple(listB))`也可以. (3认同)