python - python 中的运行时变量访问

标签 python declaration

我是Python新手。在这里,我正在测试循环中使用了varialbe wordlist 的示例。

使用前需要手动声明吗?或者它会被声明为运行时?

我什至尝试过手动声明,但它仍然是空的。

我正在遵循这个示例:http://www.sjwhitworth.com/sentiment-analysis-in-python-using-nltk/

如果我直接使用这个:

wordlist = [i for i in wordlist if not i in stopwords.words('english')]
wordlist = [i for i in wordlist if not i in customstopwords]

它给出错误:

wordlist = [i for i in wordlist if not i in stopwords.words('english')]
NameError: name 'wordlist' is not defined

我像这样手动声明了wordlist

wordlist = []

但在这种情况下它仍然为空:

wordlist = []
wordlist = [i for i in wordlist if not i in stopwords.words('english')]
wordlist = [i for i in wordlist if not i in customstopwords]

print wordlist

我在这里做错了什么?

最佳答案

以下是列表推导式在 Python 中的工作原理。假设你有一个列表 x 就像

x=[1,2,3,4]

并且您想使用列表理解来增加其值:

y=[element+1 for element in x]
#   ^               ^       ^
#element         element    list on which
#to be added                operations are
#in list of y               performed

输出:

y=[2,3,4,5]

在您的情况下,x(即wordlist)为空,因此for循环不会迭代。根据提到的link的描述 wordlist 应该是艺术家姓名的数组。

wordlist = ["Justin Timberlake", "Tay Zonday", "Rebecca Black"]

关于python - python 中的运行时变量访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25357024/

相关文章:

python - TemplateDoesNotExist 在/base.html

python - 在列表中找到第 n+n 个元素

python - pandas 仅针对正值和其他条件计算/显示数据帧 cumsum()

c - typedef 和变量名

javascript - 如何在 Parse.Cloud.define() 中声明参数

python - 将 Python 列表转换为字典的简单方法

python - 如何合并列表中的对象

c - main/error :expected ';' , ',' or ')' before numeric constant|中的函数的隐式声明

c - #ifdef(或其他预处理器指令)是否适用于函数声明(以测试函数是否存在)?

javascript - 声明不带 var 关键字的变量