2017-05-20 16 views
1

stdinはリストにテキストのスティングを返し、複数行のテキストはすべてリスト要素です。 どのようにそれらをすべて1つの単語に分割しますか?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", "") 

をそれとも、1行でそれをしたい場合:

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

関連する問題