[英]Am I interpreting this list comprehension correctly in python?
I am still fairly new to python and still have some fumbles when reading list comprehensions. 我对python还是很陌生,在阅读列表理解时仍然有些困惑。 I tried translating two list comprehensions I saw in a tutorial into its elongated form.
我尝试将在教程中看到的两个列表理解转换为它的加长形式。 Did I translate correctly?
我翻译正确吗?
list comprehension 1 清单理解1
mytokens = [ word.lemma_.lower().strip() if word.lemma_ != "-PRON-" else word.lower_ for word in mytokens ]
translation 1 翻译1
for word in mytokens:
if word.lemma_ != "-PRON-":
word.lemma_.lower().strip()
else:
word.lower_
list comprehension 2 清单理解2
mytokens = [ word for word in mytokens if word not in stopwords and word not in punctuations ]
translation 2 翻译2
for word in mytokens:
if word not in stopwords and not in punctuations:
yield word
for translation 2, I dont think "yield word" would be correct since its not a definition. 对于翻译2,我不认为“屈服词”是正确的,因为它不是一个定义。 I am guessing list comprehension 2 does the if statement and places the word back into the list mytokens so maybe it should be a .append?
我猜想列表理解2的if语句会将单词放回列表mytokens中,所以它应该是.append吗?
I think it is right. 我认为是对的。 You are looping correctly.
您正在正确循环。 However, you aren't adding the words to a list?
但是,您不是要在列表中添加单词吗? Do you mean to be doing this?
您是要这样做吗?
So for the first one you could use 所以对于第一个您可以使用
my_list = []
for word in mytokens:
if word.lemma_ != "-PRON-":
my_list.append(word.lemma_.lower().strip())
else:
my_list.append(word.lower_)
By adding them to a list like this it means you can directly compare the output of your translation and the output of the list comprehension. 通过将它们添加到这样的列表中,这意味着您可以直接比较翻译的输出和列表理解的输出。
mytokens
should be exactly the same as my_list
if done correctly. 如果正确完成,
mytokens
应该与my_list
完全相同。
Also there is a small mistake in the second translation. 在第二个翻译中也有一个小错误。 It should be:
它应该是:
for word in mytokens:
if word not in stopwords and word not in punctuations:
yield word
You could also modify this second translation to add all your words to a list. 您还可以修改第二个翻译,以将所有单词添加到列表中。
Let's simplify this: 让我们简化一下:
coll = ["Gerry", "Mary", "Sue"]
comprehended = [ word.lower() for word in coll]
def comprehender(coll):
coll_out = []
for word in coll:
coll_out.append(word.lower())
return coll_out
If you run this, you can be assured that the two are equivalent by using assert
or just return
ing comprehended == comprehender(coll)
如果运行此命令,则可以通过使用
assert
或只return
comprehended == comprehender(coll)
来确保两者等效。
This is a valid sanity check you can do on any list comprehension, you just vary this pattern to match the logic of your comprehension. 您可以对任何列表理解进行有效的健全性检查,只需更改此模式以匹配您的理解逻辑即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.