为什么整数值越高,程序运行时间就越长?

问题描述 投票:0回答:1

我正在使用此存储库中的文本文件。

f = open("words_alpha.txt")
lists =f.read()
f.close()

# word is the list of random letters
lists = lists.split()


for i in lists[:]:
  if len(i) < 3:
    lists.remove(i)

我不明白为什么每当我增加第10行的整数(

if len(i) < 3
)时,运行时间就会急剧增加(当它是3时,需要4秒才能运行,当我使用4时,需要25秒,而当运行完整的程序时,这个变化运行时间从 2 秒(如果是 2)到超过 2 分钟(当我使用 4 或更大时)。 在这种情况下,较大的值不应该不会影响任何东西,因为列表的长度相同吗?而在实际的程序中,不是应该更快吗?

python
1个回答
2
投票

因为有更多的单词长度小于 4,然后有更多的单词长度小于 3。所以要删除更多。从列表中删除的速度很慢。

尝试使用列表理解:

lists = [l for l in lists if len(l) < 3]
© www.soinside.com 2019 - 2024. All rights reserved.