【问题标题】:Why is my use of any method in Python so slow?为什么我在 Python 中使用任何方法都这么慢?
【发布时间】:2016-12-07 17:19:56
【问题描述】:

我正在尝试搜索字符串(句子)列表并检查它们是否包含一组特定的子字符串。为此,我使用 Python 的“任意”函数

sentences = ["I am in London tonight",
                   "I am in San Fran tomorrow",
                   "I am in Paris next Wednesday"]

# Imagine the following lists to contain 1000's of strings 
listOfPlaces = ["london", "paris", "san fran"] 
listOfTimePhrases = ["tonight", "tomorrow", "week", "monday", "wednesday", "month"]

start = time.time()

sntceIdxofPlaces = [pos for pos, sent in enumerate(sentences) if any(x in sent for x in listOfPlaces)]
sntceIdxofTimes = [pos for pos, sent in enumerate(sentences) if any(x in pos for x in listOfTimePhrases)]

end = time.time()

print(end-start)

如果您想象我的列表非常大,我发现我在两个“任何”语句上经过的时间相当长。对于两个这样的“任何”查询,我得到大约 2 秒的时间。您知道为什么要花这么长时间吗?您知道有什么方法可以使代码更快吗?

谢谢

【问题讨论】:

  • @MorganThrapp Brainfart 对此。没有查看sent的内容

标签: python performance


【解决方案1】:

不要将您的sentences 枚举两次。你可以对你的句子进行一次循环检查。

sntceIdxofPlaces = []
sntceIdxofTimes = []
for pos, sent in enumerate(sentences):
    if any(x in sent for x in listOfPlaces):
        sntceIdxofPlaces.append(pos)
    if any(x in sent for x in listOfTimePhrases):
        sntceIdxofTimes.append(pos)

【讨论】:

  • 这个答案结合使用数据列表的集合是要走的路。
  • @joeb 谢谢你。我刚刚使用其他人友善给出的建议测试了单个 for 循环。我不确定我是不是很傻,但没有什么收获。
  • 根据我的计时测试(foo 与foo2 在下面的答案中),从中获得的收益可以忽略不计。使用集合也没有任何好处,因为我们必须迭代集合,而不是测试它们的成员资格。
  • 嗨,我意识到我没有看到太多收获的原因可能是因为我的句子列表总是很短(少于 6 个)。因此,在我的情况下,两次枚举的开销并不算太糟糕。谢谢
【解决方案2】:

有一个严重的低效率。也就是说,您没有使用集合。检查集合中的成员是一个非常有效的操作(O(1) vs O(n) 对于列表)。

sentences = ["I am in London tonight",
                   "I am in San Fran tomorrow",
                   "I am in Paris next Wednesday"]

# Imagine the following lists to contain 1000's of strings 
listOfPlaces = {"london", "paris", "san fran"} 
listOfTimePhrases = {"tonight", "tomorrow", "week", "monday", "wednesday", "month"}

start = time.time()

sntceIdxofPlaces = [pos for pos, sent in enumerate(sentences) if any(x in sent for x in listOfPlaces)]
sntceIdxofTimes = [pos for pos, sent in enumerate(sentences) if any(x in sent for x in listOfTimePhrases)]

end = time.time()

print(end-start)

【讨论】:

  • 谢谢摩根。我刚刚使用集合进行了测试,我的任何代码都快了大约 10 倍左右。如果我使用 sent.split() 我不会拆分更长的字符串“San Fran”吗?我可能会在搜索中错过他们吗?再次感谢您
  • 几乎任何时候您有一组静态的无序数据进行查找,都值得使用一组。对集合的查找是 O(1) 操作,而对于列表是 O(n)。
  • sent.split() 方法可以捕获大多数情况,但不幸的是错过了"san fran",因为它被分成了两个词。
  • @jez 你说得对,我完全错过了。我删除了那部分答案。
【解决方案3】:

这里有三种替代方法,它们使用查找每个句子而不是查找目标短语列表。它们都随着目标短语列表的长度而严重扩展。

sentences = [
    "I am the walrus",
    "I am in London",
    "I am in London tonight",
    "I am in San Fran tomorrow",
    "I am in Paris next Wednesday"
]
sentences *= 1000   # really we want to examine large `listOfPlaces` and `listOfTimePhrases`, but these must be unique and so are harder to generate---this is an quicker dirtier way to test timing scalability

# Imagine the following lists to contain 1000's of strings 
listOfPlaces = {"london", "paris", "san fran"}
listOfTimePhrases = {"tonight", "tomorrow", "week", "monday", "wednesday", "month"}

# preprocess to guard against substring false positives and case-mismatch false negatives:
sentences = [ ' ' + x.lower() + ' ' for x in sentences ]
listOfPlaces = { ' ' + x.lower() + ' ' for x in listOfPlaces }
listOfTimePhrases = { ' ' + x.lower() + ' ' for x in listOfTimePhrases }

#listOfPlaces = list( listOfPlaces )
#listOfTimePhrases = list( listOfTimePhrases )

def foo():
    sntceIdxofPlaces = [pos for pos, sentence in enumerate(sentences) if any(x in sentence for x in listOfPlaces)]
    sntceIdxofTimes  = [pos for pos, sentence in enumerate(sentences) if any(x in sentence for x in listOfTimePhrases)]
    return sntceIdxofPlaces, sntceIdxofTimes

def foo2():
    sntceIdxofPlaces = []
    sntceIdxofTimes = []
    for pos, sentence in enumerate(sentences):
        if any(x in sentence for x in listOfPlaces): sntceIdxofPlaces.append(pos)
        if any(x in sentence for x in listOfTimePhrases): sntceIdxofTimes.append(pos)
    return sntceIdxofPlaces, sntceIdxofTimes

def foo3():
    sntceIdxofPlaces = []
    sntceIdxofTimes = []
    for pos, sentence in enumerate(sentences):
        for x in listOfPlaces:
            if x in sentence: sntceIdxofPlaces.append(pos); break
        for x in listOfTimePhrases:
            if x in sentence: sntceIdxofTimes.append(pos); break
    return sntceIdxofPlaces, sntceIdxofTimes

以下是计时结果:

In [171]: timeit foo()
100 loops, best of 3: 15.6 ms per loop

In [172]: timeit foo2()
100 loops, best of 3: 16 ms per loop

In [173]: timeit foo3()
100 loops, best of 3: 8.07 ms per loop

any() 似乎效率低下,这让我很惊讶。即使早早找到匹配并且答案已经知道,它也可能将其输入生成器运行到最后。我知道它不应该像这样工作,但我无法解释 foo2() 和 foo3() 之间运行时间的因素 2 差异,这似乎给出了相同的输出。

另外:由于 listOfPlaces 和 listOfTimePhrases 正在被迭代,而不是针对成员资格进行测试,因此无论它们是 sets 还是 lists 似乎都不会影响时间。

【讨论】:

  • any 函数不会像基于 this 答案那样执行...
  • 我也不会这么认为,但计时结果是惊人的。而且它们是可重复的(我刚刚在 2013 MacBook 上的 anaconda Python 2.7.12 下以不同的顺序运行了它们几次)。这三个函数似乎返回相同的输出,所以如果其中一个有错误,我看不到它。
  • 如果我没看错的话,这里会发现类似的东西dotnetperls.com/any-python
【解决方案4】:

对listOfPlaces 和listOfTimePhrases 使用集合而不是列表。集合的查找时间要快得多:

listOfPlaces = set(["london", "paris", "san fran"])
listOfTimePhrases = set(["tonight", "tomorrow", "week", "monday", "wednesday", "month"])

【讨论】:

    【解决方案5】:

    这是一个利用快速查找listOfPlaces 和listOfTimePhrases 作为sets 的优势,同时考虑可能的多词短语。即使listOfPlaces 和listOfTimePhrases 包含数千个元素,它也能快速运行。

    sentences = [
        "I am the walrus",
        "I am in London",
        "I am in London tonight",
        "I am in San Fran tomorrow",
        "I am in Paris next Wednesday"
    ]
    sentences *= 1000
    
    # Imagine the following lists to contain 1000's of strings 
    placePhrases = {"london", "paris", "san fran"}
    timePhrases = {"tonight", "tomorrow", "week", "monday", "wednesday", "month"}
    
    
    # preprocess to guard against case-mismatch false negatives:
    sentences = [ x.lower() for x in sentences ]
    placePhrases = { x.lower() for x in placePhrases }
    timePhrases = { x.lower() for x in timePhrases }
    
    # create additional sets in which incomplete phrases can be looked up:
    placePrefixes = set()
    for phrase in placePhrases:
        words = phrase.split()
        if len(words) > 1:
            for i in range(1, len(words)):
                placePrefixes.add(' '.join(words[:i]))
    timePrefixes = set()
    for phrase in timePhrases:
        words = phrase.split()
        if len(words) > 1:
            for i in range(1, len(words)):
                timePrefixes.add(' '.join(words[:i]))
    
    def scan(sentences):
        sntceIdxofPlaces = []
        sntceIdxofTimes = []
        for pos, sentence in enumerate(sentences):
            hasPlace = hasTime = False
            placePrefix = timePrefix = ''
            for word in sentence.split():
                if not hasPlace:
                    placePhrase = placePrefix + (' ' if placePrefix else '') + word
                    if placePhrase in placePrefixes:
                        placePrefix = placePhrase
                    else:
                        placePrefix = ''
                        if placePhrase in placePhrases: hasPlace = True
                if not hasTime:
                    timePhrase = timePrefix + (' ' if timePrefix else '') + word
                    if timePhrase in timePrefixes:
                        timePrefix = timePhrase
                    else:
                        timePrefix = ''
                        if timePhrase in timePhrases: hasTime = True
                if hasTime and hasPlace: break
            if hasPlace: sntceIdxofPlaces.append(pos)
            if hasTime: sntceIdxofTimes.append(pos)
        return sntceIdxofPlaces, sntceIdxofTimes
    

    【讨论】:

      【解决方案6】:

      我设法使用 scikit 的 countvectorise 函数找到了一种更快的方法

      sentences = ["I am in London tonight",
                     "I am in San Fran tomorrow",
                     "I am in Paris next Wednesday"]
      
      listOfPlaces = ["london", "paris", "san fran"]
      
      cv = feature_extraction.text.CountVectorizer(vocabulary=listOfPlaces)
      
      # We now get in the next step a vector of size len(sentences) x len(listOfPlaces)           
      taggedSentences = cv.fit_transform(sentences).toarray()
      
      aggregateTags = np.sum(taggedSentences, axis=1)
      

      我们最终得到一个长度为 len(sentences) 乘以 1 的向量,其中每一行都有一个单词列表中单词出现在每个句子中的次数的计数。

      我发现大型数据集的结果非常快,例如(0.02s)

      【讨论】:

        猜你喜欢
        • 2016-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-13
        • 2018-10-08
        相关资源
        最近更新 更多