【问题标题】:how to access a list inside a function without returning it?如何访问函数内部的列表而不返回它?
【发布时间】:2020-11-19 04:08:02
【问题描述】:

所以我不小心忘记在我的方法中包含一个 return 语句,它在 10 小时后才运行完毕,所以我不想再次运行它。有没有办法我可以在这个函数中访问wordlist?

def rm_foreign_chars(corpus):
    wordlist=[]
    for text in corpus:
        for sentence in sent_tokenize(text):
            wordlist.append(sentence)
            for word in word_tokenize(sentence):
                for c in symbols:

                    if c in word:
                        if sentence in wordlist:
                            wordlist.remove(sentence)
                            break

Symbols 是一个符号列表:symbols = '฿‑‒–—―‖†‡•‰⁰⁷⁸₂₣℃™→↔∆∙≤⋅─■□▪►▼●◦◾★☎☺♣♦✓✔❖❗➡⠀ⱻ�ₒ'1

【问题讨论】:

  • 不。没了。
  • 修复您的错误并开始重新运行。
  • 翻录列表,这就是为什么你在实现之前测试你的功能!
  • 函数完成后,局部变量会被垃圾回收,所以可能不会。对于未来的重播,与其将每个句子都添加到列表中,然后如果它的任何单词中包含某个符号,则将其删除,为什么不简单地将每个没有该符号的句子写入某个文件呢?没有丢失结果的风险,即使是中途也不复杂,所以它应该更快。
  • 您有一种非常复杂且低效的过滤带有符号的句子的方法。它做了很多不必要的工作。清理它,下一次运行应该比 10 小时快很多。

标签: python list


【解决方案1】:

不幸的是,如果不使用一些非常老套的方法并在内存中四处寻找,就无法访​​问函数之外的wordList。相反,我们可以专注于让您的功能更快。这是我想出的:

def rm_foreign_chars(corpus):
    wordlist=[]
    for text in corpus:
        for sentence in sent_tokenize(text):
            if not any(c in word for word in word_tokenize(sentence) for c in symbols):
                wordlist.append(sentence)
    return wordlist

您也可以将wordlist 设为全局变量。我建议将其设为全局的唯一原因是函数运行的时间长短(27 分钟仍然很长)如果函数在完成前失败,您仍然可以从 wordlist 获得一些东西。

def rm_foreign_chars(corpus):
    global wordlist
    for text in corpus:
        for sentence in sent_tokenize(text):
            if not any(c in word for word in word_tokenize(sentence) for c in symbols):
                wordlist.append(sentence)
    return wordlist

wordlist=[]

rm_foreign_chars(...)
# use wordlist here

【讨论】:

  • 谢谢,从 10 小时缩短到 27 分钟!开销是由 remove() 函数引起的吗?
  • @mojbius 可能是 remove 和 if sentence in wordlist 的组合。很高兴它对你很有效
【解决方案2】:

如果不返回列表,则无法执行此操作。另一种方法是创建一个包含该函数的类并将列表存储为self 的属性。

class Characters:
    def __init__(self, corpus):
        self.corpus = corpus
        self.wordlist = []

    def foreign_chars(self):
        pass
        # Function code goes here
        # Be sure to replace corpus and wordlist
        # With their respective self attributes

chars = Characters()
chars.foreign_chars()
words = chars.wordlist

请参考其他答案和 cmets 来优化您的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-24
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    相关资源
    最近更新 更多