【问题标题】:Fastest way to check if a item is in a list - Python [duplicate]检查项目是否在列表中的最快方法-Python [重复]
【发布时间】:2017-05-11 06:56:46
【问题描述】:

我在用 python 制作词汇表时遇到了问题。我的代码遍历了大约 2.3MB 文档中的每个单词,并检查该单词是否在字典中,如果不是,则附加到列表中

问题是,它需要很长时间(我什至还没有完成)。我该如何解决这个问题?

代码:

words = [("_", "hello"), ("hello", "world"), ("world", "."), (".", "_")] # List of a ton of tuples of words
vocab = []
for w in words:
    if not w in vocab:
        vocab.append(w)

【问题讨论】:

  • 你有多少字?为什么不使用set() 而不是列表?
  • 您能否提供您正在检查的单词的副本。
  • words 实际上是一个元组列表(n-gram)

标签: python python-2.7 list python-3.x


【解决方案1】:

除非您需要vocab 有特定的订单,否则您可以这样做:

vocab = set(words)

【讨论】:

  • 但是如果一个单词出现了不止一次,那是单词列表。我不想在我的词汇表中有任何重复。 @AlexHall
  • @N.Chalifour 是的,集合没有重复项。
  • 谢谢!它就像一个魅力。
【解决方案2】:

下面是测试for循环和set()的执行时间对比:

import random
import time
import string


words = [''.join(random.sample(string.letters, 5)) for i in range(1000)]*10  # *10 to make duplicates!

vocab1 = []

t1 = time.time()
for w in words:
    if w not in vocab1:
        vocab1.append(w)
t2 = time.time()

t3 = time.time()
vocab2 = set(words)
t4 = time.time()

print t2 - t1
print t4 - t3

输出:

0.0880000591278  # Using for loop
0.000999927520752  # Using set()

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 2012-05-20
    • 2015-01-10
    • 2021-07-17
    • 2023-03-22
    • 2022-06-06
    • 2018-11-03
    • 2010-12-13
    • 2017-12-21
    相关资源
    最近更新 更多