【问题标题】:How to check if there are any matches between two lists of sublists using regular expressions?如何使用正则表达式检查两个子列表列表之间是否有任何匹配?
【发布时间】:2014-02-22 08:39:07
【问题描述】:

我有两个子列表列表,我想检查两个列表的子列表中的一个项目是否与另一个列表匹配?

例如,我想看看索引 0 处的任何子列表是否出现在索引 0 处的另一个列表中

lsta = [['aaa','bbb','ccc'],['xxx','bbb','ccc'],['eee','bbb','ccc']]
lstb = [['aaa','b','2'],['xxx','ddd','efe']]

如果索引 1 中的任何项目出现在 lstb 中的索引 1 处,返回 lsta 中所有项目的最快方法是什么? :

Desired_List = [['aaa','bbb','ccc'],['xxx','bbb','ccc']]

对于我的大列表来说,For-Loops 太慢了,所以我想知道是否有更快的方法?

这基本上是我想要完成的任务,但速度更快

Desired_List = []
for x in lsta:
    for y in lstb:
        if re.search(x[0],str(y)):
            Desired_List.append(x)

或者还有其他方法可以完成这项任务吗?也许是列表理解?

也许还有,但不确定是否更快:

   Desired_List = filter(lambda x: re.search(str(x[0]),str(lstb)),lsta)

【问题讨论】:

  • 你能发布你的for循环吗?请注意,这是一个 n^2 算法(lsta 中的每个元素都需要与 lstb 中的每个元素进行比较),尽管如果您进行大量执行,您可以使用更好的数据结构来加速它。跨度>
  • 如何改进这里的数据结构?

标签: python regex list sublist


【解决方案1】:

对出现在lstb的子列表的索引0处的项目进行set,然后使用该集合快速确定lsta的匹配项目:

b_set = set(sublist[0] for sublist in lstb)
desiredlist = [sublist for sublist in lsta if sublist[0] in b_set]

请注意,您的for 循环解决方案是错误的:

>>> lsta = [[', ', '', '']]
>>> lstb = [['a', 'b', 'c']]
>>> Desired_List = []
>>> for x in lsta:
...     for y in lstb:
...         if re.search(x[0],str(y)):
...             Desired_List.append(x)
...
>>> Desired_List
[[', ', '', '']]

【讨论】:

  • @Chris:已更正和测试。
【解决方案2】:

您应该能够通过使用lstb 构建一个字典来加快速度:

dictb = {el[0]: el for el in lstb}
Desired_List = [el for el in lsta if el[0] in dictb]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 2021-11-27
    • 2012-12-16
    • 1970-01-01
    相关资源
    最近更新 更多