用于列表列表的Python函数
我想找出句子中单词的长度,并以列表的形式返回结果 大概是用于列表列表的Python函数,python,list,function,Python,List,Function,我想找出句子中单词的长度,并以列表的形式返回结果 大概是 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
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]]
知道我在哪里搞砸了吗?我讨厌总想着这些不断变化的清单。更具python风格的版本包含列表理解:
result = [
[len(word) for word in sentence.split(" ")]
for sentence in sentences]
更简明的解决办法是:
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]]
说明:
lucky中s的将遍历lucky中的所有字符串。使用s.split()
我们然后将每个字符串s
拆分为它所组成的单词。然后使用len(w)
,我们获得s中每个单词w
的长度(字符数)。您的问题中的split()
给出了代码失败的原因。下面是另一个利用以下功能的解决方案:
Python3中,如果您希望看到预期的输出,您将必须调用map
对象
>>> 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]]
除了在循环中调用x.split
而不是i.split
之外,您的代码工作得非常好,并且给出了正确的结果。