从外部功能访问列表

从外部功能访问列表

问题描述:

我在function1内部创建了一个列表.我希望能够在function2中访问和修改它.没有全局变量,我该怎么办?

I have a list that I create inside of function1. I want to be able to access and modify it in function2. How can I do this without a global variable?

两个函数都不嵌套在另一个函数中,我需要能够针对多个函数中的多个列表进行概括.

Neither function is nested within the other and I need to be able to generalize this for multiple lists in several functions.

我希望能够使用其他功能访问word_listsentence_starter.

I want to be able to access word_list and sentence_starter in other functions.

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')

您应该将其重构为一个类:

You should refactor this as a class:

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()
...