[英]Trouble with understanding list comprehension
def reverse_words(text): return " ".join([x[::-1] for x in text.split(" ")])
我对这里的列表理解和 for 循环之间的区别有点困惑。
for x in text.split(" "): return " ".join(x[::-1])
我认为这两个会是相同的,但他们有不同的输出。 有人可以解释为什么吗?
从:
def reverse_words(text): return " ".join([x[::-1] for x in text.split(" ")])
至
def reverse_word(text): output_list = [] for x in text.split(" "): output_list.append(x[::-1]) return " ".join(output_list)
然后让我们仔细看看“奇怪的线条”,例如x[::-1]
。
x[::-1]
?这是反转列表项的捷径,例如
>>> x = [1,2,3,4,5] >>> x[::-1] [5, 4, 3, 2, 1]
现在在 string 类型:
>>> x = "abcde" >>> x[::-1] 'edcba'
有关更多详细信息,请参阅
text.split(" ")
通常这用于 NLP(自然语言处理)任务将句子拆分为单词,也就是word tokenization
,例如
>>> text = "This is a sentence" >>> text.split(" ") ['This', 'is', 'a', 'sentence']
所以text.split(" ")
粗略地返回“单个单词”(“单词标记化”有很多细微差别,所以str.split(" ")
对于英文文本来说是最简单的)。
text.split(" ")
与x[::1]
结合让我们在这里使用一些比x
更合理的变量名,本质上我们正在这样做:
# Word tokenization, so "abc def" -> ["abc", "def"] for word in text.split(" "): # Reverse each word, so "abc" -> "cba" print(word[::-1])
" ".join(...)
的最后一部分是什么? str.join
是来自https://docs.python.org/3/library/stdtypes.html#str.join 的 function; 它的 function 是将列表中的项目与您想要的一些str
连接起来。
这里有一些例子:
>>> list_of_words = ["abc", "def", "xyz"] >>> type(list_of_words) <class 'list'> >>> " ".join(list_of_words) 'abc def xyz' >>> "-".join(list_of_words) 'abc-def-xyz' >>> "-haha-".join(list_of_words) 'abc-haha-def-haha-xyz' >>> output = " ".join(list_of_words) >>> type(output) <class 'str'>
我们得到这个:
def reverse_words_in_text(text): # Keep a list of the reversed words. output_list_of_words = [] # Word tokenization, so "abc def" -> ["abc", "def"] for word in text.split(" "): # Reverse each word, so "abc" -> "cba" output_list_of_words.append(word[::-1]) # Join back the tokens into a string. return " ".join(output_list_of_words)
如果你喜欢一个班轮:
>>> reverse_words = lambda text: " ".join(text[::-1].split()[::-1]) >>> reverse_words('abc def ghi') 'cba fed ihg'
但这只会使代码更加不可读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.