Accessing List from outside function

心不动则不痛 提交于 2019-12-23 06:49:03

问题


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.

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

回答1:


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

Usage

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



回答2:


You can simply use the list that first function creates as an argument of second function:

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

But if you need to use the list in multiple places (being processed by multiple functions) then storing it as a variable is not really a bad thing - even more, if your list generating function does some computing to generate the list, you're saving CPU by computing it only once.




回答3:


If you do not want to a) use a global or b) return the list and pass it about, then you will have to use a class and hold your list in there.

The class route is best




回答4:


Functions can have attribute values (For examples, see question 338101.)

In the current context, you could save and reference items like prefix_dict, word_list, sub_list, and word as individual attributes of whichever function computes them, as illustrated in the following example. However, use of a class, as suggested in other answers, is more likely to be understandable and maintainable in the long-term .

For example:

In [6]: def fun1(v):
    fun1.li = range(v,8)
    return v+1
   ...: 

In [7]: def fun2(v):
    fun2.li = range(v,12) + fun1.li
    return v+2
   ...: 

In [8]: fun1(3)
Out[8]: 4

In [9]: fun2(6)
Out[9]: 8

In [10]: fun2.li
Out[10]: [6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7]


来源:https://stackoverflow.com/questions/14676000/accessing-list-from-outside-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!