0

私は以前にスタックオーバーフローを使用したことがありません。通常、数学と物理のセクションにとどまります。私は原子炉の物理学者であり、プログラマーではありません。これは文字通り、Python 2 をいじる最初の 1 週間なので、私を非難しないでください。

forループを使用して、小さな段落の単語の長さを含むリスト「wordLenLi」を作成することになっています。短い段落はバッチ ファイルにあります

これは私が試したものです。また、append() メソッドをいじってみました。この小さなちっぽけな本はあまり正義をしません。

st = '''April is the crueles month, breeding
Lilacs out of the dead land, mixing
Memory and desire, stirring
Dull roots with spring rain.'''

x = st.upper()

wordLi = x.split(' ')

for n in wordLi:    
    z = len(n)
    WordLenli = z.split()
    print wordLenLi
4

2 に答える 2

2

以下はリスト内包表記です。リスト内包表記は、基本的に 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

于 2013-05-09T10:36:56.687 に答える