2017-05-20 234 views
1

因此stdin將一串文本返回到一個列表中,並且多行文本都是列表元素。 你如何將它們全部分成單個單詞?python如何分割列表中的文本

mylist = ['this is a string of text \n', 'this is a different string of text \n', 'and for good measure here is another one \n'] 

想輸出:

newlist = ['this', 'is', 'a', 'string', 'of', 'text', 'this', 'is', 'a', 'different', 'string', 'of', 'text', 'and', 'for', 'good', 'measure', 'here', 'is', 'another', 'one'] 

回答

3

您可以使用簡單的列表理解,如:

newlist = [word for line in mylist for word in line.split()]

這產生:

>>> [word for line in mylist for word in line.split()] 
['this', 'is', 'a', 'string', 'of', 'text', 'this', 'is', 'a', 'different', 'string', 'of', 'text', 'and', 'for', 'good', 'measure', 'here', 'is', 'another', 'one'] 
+1

謝謝你,這是完美的。更好的是,你已經勾畫出一個全新的Python概念供我學習。 – iFunction

0

你可能只是這樣做:

words = str(list).split() 

所以你把列表變成一個字符串,然後用空格鍵分隔它。 然後,你可以通過執行刪除/ N的:

words.replace("/n", "") 

或者,如果你想這樣做在同一行:

words = str(str(str(list).split()).replace("/n", "")).split() 

只是說這可能不會在Python 2

0

工作再說列表理解上面的答案,我擔保,你也可以做一個for循環:

#Define the newlist as an empty list 
newlist = list() 
#Iterate over mylist items 
for item in mylist: 
#split the element string into a list of words 
itemWords = item.split() 
#extend newlist to include all itemWords 
newlist.extend(itemWords) 
print(newlist) 

最終您的newlist將包含所有元素中的所有分詞mylist

但是,Python列表的理解看起來好多了,你可以用它做很棒的事情。點擊此處瞭解:

https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

+0

是的,謝謝你把我放到這裏,我整個週末都在研究它。這是解決問題的好方法。我主要關心的是速度和效率,在我看來,列表解析是構建Python語言的一部分將比循環更快。 – iFunction