【问题标题】:how to my python script for loop run faster and use less loop?如何让我的循环 python 脚本运行得更快并使用更少的循环?
【发布时间】:2020-10-05 23:27:14
【问题描述】:

我想检查两个单词是否同时存在于同一个列表中。

例如

我有一个单词列表,就像

word_list = [I have a dream, I am a dreamer]

并有一个名为 df 的数据框

df

# word1  word2
#  have   dream
#  basketball player

我想同时检查两个单词是否存在于同一个列表中。所以我这样写了我的代码

for index, row in df.iterrows():
    text = []
    tokenized = word_list.split()
    for tokenized_word in tokenized:
        if row["word1"] == tokenized_word:
                    for tokenized_word in tokenized:
                        if row["word2"] == tokenized_word:
                            text.append(word_list)

如果列表有很多元素并且数据框有很多单词,则运行此代码将花费很多时间。 无论如何要加快我的代码?

【问题讨论】:

  • if row["word1"] in tokenized and row["word2"] in tokenized: text.append(word_list) 是您要找的吗?如果您需要更快、更复杂的解决方案,Pandas 也为您提供了一些工具。
  • (1) 建立一个单词列表。 (2) 计算每个单词出现的次数。 (3) 标记任何出现多次的“有趣”词。

标签: python


【解决方案1】:

我会这样做:

tokens = set(word_list.split())
text = [
    word_list for _, row in df.iterrows() 
    if row["word1"] in tokens and row["word2"] in tokens
]

由于word_list 永远不会改变,您只需要构建一个set 一次,然后每次word in tokens 检查都是常数时间,而不需要对整个列表进行迭代。

请注意,我不确定这是否真的是您要构建的列表(word_list 的同一副本一遍又一遍地重复),但这是您的原始循环所做的。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    相关资源
    最近更新 更多