【发布时间】:2017-08-19 04:01:31
【问题描述】:
所以我有一个列表,其中每个元素都有一个句子形式的字符串,就像这样
a = ["This is a sentence with some words.", "And this is a sentence as well.", "Also this right here is a sentence."]
我想要对这个列表做的是只保留每个字符串的第三个和第四个单词,所以最后我想要一个类似的列表
b = ["a sentence", "is a", "right here"]
我认为要做的第一件事是在空格后拆分列表,所以像
for x in a:
x.split()
但是我对如何继续有点困惑。上面的循环应该基本上每个句子产生一个列表,其中每个单词都是一个自己的元素。我想过这样做
e = []
for x in a:
x.split()
a = x[0:2]
a = x[2:]
e.append(a)
但不是删除单词,而是删除字符,我得到以下输出
['is is a sentence with some words.', 'd this is a sentence as well.', 'so this right here is a sentence.']
我不确定它为什么会产生这种行为。我已经坐了一段时间了,可能错过了一些非常愚蠢的事情,所以我非常感谢一些帮助。
【问题讨论】:
-
x.split()的结果不会以任何方式存储,并且效果不会像您想象的那样发生在 x 中。