【发布时间】:2017-07-25 07:29:23
【问题描述】:
我想查找句子中单词的长度,并将结果作为列表返回。
类似
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]]
知道我在哪里搞砸了吗?
【问题讨论】:
-
除了您在循环中调用
x.split而不是i.split之外,您的代码工作得非常好并且给出了正确的结果。