从外部功能访问列表

编程入门 行业动态 更新时间:2024-10-11 01:16:20
本文介绍了从外部功能访问列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在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_list和sentence_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() ...

更多推荐

从外部功能访问列表

本文发布于:2023-11-13 04:29:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:功能   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!