2017-03-05 55 views
2

我想查找句子中单词的长度,并将结果作为列表列表返回。列表列表的Python函数

因此,像

lucky = ['shes up all night til the sun', 'shes up all night for the fun', 'hes up all night to get some', 'hes up all night to get lucky'] 

应该成为

[[4, 2, 3, 5, 3, 3, 3], [4, 2, 3, 5, 3, 3, 3], [3, 2, 3, 5, 2, 3, 4], [3, 2, 3, 5, 2, 3, 5]] 

下面的代码

result =[] 

def sentancewordlen(x) 
    for i in x: 
     splitlist = x.split(" ") 
     temp=[] 
     for y in splitlist: 
       l = len(y) 
       temp.append(l) 
     result.append(temp) 
sentancewordlen(lucky) 

出来的东西是最后一句的结果,在其自己的每个长度名单。

[[3], [2], [3], [5], [2], [3], [5]] 

任何想法,我很愚蠢吗?

+3

除此之外,你叫'x.split',而不是'i.split'在循环的事实,你的代码作品绝对好,并给出正确的结果。 –

回答

4

我讨厌一起思考这些变化的列表。在更Python版本与列表理解:

result = [ 
    [len(word) for word in sentence.split(" ")] 
    for sentence in sentences] 
1

一个更简洁的解决方案是:

lengths = [[len(w) for w in s.split()] for s in lucky] 

输出:

[[4, 2, 3, 5, 3, 3, 3], [4, 2, 3, 5, 3, 3, 3], [3, 2, 3, 5, 2, 3, 4], [3, 2, 3, 5, 2, 3, 5]] 

说明:

for s in lucky将通过所有的迭代幸运的字符串。随着s.split(),我们然后将每个字符串s分成它组成的单词。使用len(w),然后我们获得s.split()中每个单词w的长度(字符数)。

0

The comment在你的问题中给你你的代码失败的原因。这是另一种解决方案充分利用使用map

Python 3中,你得到map对象,你将不得不调用,如果你想看到的输出,你期望在list

>>> res = [list(map(len, x.split())) for x in lucky] 
>>> res 
[[4, 2, 3, 5, 3, 3, 3], [4, 2, 3, 5, 3, 3, 3], [3, 2, 3, 5, 2, 3, 4], [3, 2, 3, 5, 2, 3, 5]] 

Python 2里会给你从哪打来map列表:

>>> res = [map(len, x.split()) for x in lucky] 
>>> res 
[[4, 2, 3, 5, 3, 3, 3], [4, 2, 3, 5, 3, 3, 3], [3, 2, 3, 5, 2, 3, 4], [3, 2, 3, 5, 2, 3, 5]]