从外部函数访问列表

0 投票
4 回答
18331 浏览
提问于 2025-04-17 14:37

我在function1里面创建了一个列表,现在我想在function2里面访问和修改这个列表。请问我该怎么做,才能不使用全局变量呢?

这两个函数并不是嵌套在一起的,我还希望能把这个方法推广到多个列表和多个函数中。

我想在其他函数里访问word_listsentence_starter这两个列表。

def Markov_begin(text):
    print create_word_lists(text)
    print pick_starting_point(word_list)
    return starting_list


def create_word_lists(filename):
   prefix_dict = {}    
   word_list = []
   sub_list = []
   word = ''

   fin = open(filename)
   for line in fin:
      the_line = line.strip()
      for i in line:
           if i not in punctuation:
               word+=(i)
           if i in punctuation:
               sub_list.append(word)
               word_list.append(sub_list)
               sub_list = []
               word = ''
      sub_list.append(word)
      word_list.append(sub_list)
   print 1
   return word_list

def pick_starting_point(word_list):
    sentence_starter = ['.','!','?']
    starting_list = []
    n = 0
    for n in range(len(word_list)-1):
        for i in word_list[n]:
            for a in i:
                if a in sentence_starter:
                    starting_list += word_list[n+1]
    print 2                
    return starting_list



def create_prefix_dict(word_list,prefix_length):
    while prefix > 0:
        n = 0
        while n < (len(word_list)-prefix):
            key = str(''.join(word_list[n]))
            if key in prefix_dict:
                prefix_dict[key] += word_list[n+prefix]
            else:
                prefix_dict[key] = word_list[n+prefix]
           n+=1
       key = ''
       prefix -=1

print Markov_begin('Reacher.txt')

4 个回答

0

如果你不想 a) 使用全局变量,或者 b) 返回列表然后到处传递它,那你就得用一个类,把你的列表放在里面。

用类的方法是最好的选择。

3

你可以直接把第一个函数创建的列表当作第二个函数的参数来用:

def some_list_function():
  # this function would generate your list
  return mylist

def some_other_function(mylist):
  # this function takes a list as an argument and process it as you want
  return result

some_other_function(some_list_function())

不过,如果你需要在多个地方使用这个列表(比如被多个函数处理),那么把它存成一个变量其实并不是坏事。更重要的是,如果你的列表生成函数需要进行一些计算来生成这个列表,那你只计算一次就能节省CPU的使用。

4

你应该把这个重构成一个类:

class MyWords(object):
  def __init__(self):
    self.word_list = ... #code to create word list

  def pick_starting_point(self):
    # do something with self.word_list
    return ...

使用方法

words = MyWords()
words.pick_starting_point()
...

撰写回答