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

2024-04-29 05:28:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我举个例子:

listA = ['banana', 'apple', 'appleRed', 'melon_01', 'appleGreen', 'Orange', 'melon_03']
listB = ['apple', 'melon']

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

结果应该是:

^{pr2}$

我可以在2for循环中使用if循环比较。就像

for item in listA:
    for fruit in listB:
        if item.startswith(fruit):
            listResult.append(item)
            break

不过,我想知道是否有捷径可供这项行动,因为这可能需要更多的时间进行大名单比较。在


Tags: in元素apple列表forifitem例子
3条回答

使用列表理解和any生成器:

[item for item in listA if any(item.startswith(fruit) for fruit in listB)]

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

^{pr2}$

这比第一个解决方案快得多,几乎与@iguanaut提出的regex解决方案一样快(但更简洁易读):

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
listResult = [ i for i in listA if any( i.startsWith( j ) for j in listB ) ]

如果listB中的项目相对较少,则可以相当有效地将其转换为正则表达式:

import re
regex = re.compile(r'^(?:%s)' % '|'.join(listB))
filter(regex.match, listA)

这是我想到的第一件事,但我想其他人会有其他想法。在

注意,使用列表理解的其他答案当然是完美和合理的。我想知道你是否有一个稍微快一点的方法。再次强调,对于一般情况,这种解决方案可能并不总是更快,但在这种情况下,它可以稍微:

^{pr2}$

相关问题 更多 >