以下はリスト内包表記です。リスト内包表記は、基本的に for ループを記述するための強力な省略形です。基本的なリスト内包表記は の形式を取ります[expr for variable in iterable]
。の各値をiterable
調べて に割り当てvariable
、 の結果をリストに格納しexpr
ます。そう
WordLenLi = [len(word) for word in st.split()]
print(WordLenLi)
プロデュース
>>>
[5, 2, 3, 7, 6, 8, 6, 3, 2, 3, 4, 5, 6, 6, 3, 7, 8, 4, 5, 4, 6, 5]
for ループとしては、次のようになります。
WordLenLi = []
for word in st.split(): #for each word in a list of words
WordLenLi.append(len(word)) #insert the length of the word into WordLenLi
代わりに、デモンストレーションとして:
WordLenLi = [(word,len(word)) for word in st.split()]
print(WordLenLi)
>>>
[('April', 5), ('is', 2), ('the', 3), ('crueles', 7), ('month,', 6), ('breeding', 8), ('Lilacs', 6), ('out', 3), ('of', 2), ('the', 3), ('dead', 4), ('land,', 5), ('mixing', 6), ('Memory', 6), ('and', 3), ('desire,', 7), ('stirring', 8), ('Dull', 4), ('roots', 5), ('with', 4), ('spring', 6), ('rain.', 5)]
最初の理解よりも短くすることもできます。
WordLenLi = map(len,st.split())
またst.split()
、Jon Clement の提案に従って、次のようなものに置き換えたいと思います。
re.findall(r'\b[\w\d%s]+\b' % string.punctuation,st)
を介してreおよびstringモジュールをインポートする必要がありますimport re,string
。