2

I want to find the lengths of words in sentences, and return the results as a list of lists.

So something like

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']

should become

[[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]]

Here's the code

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)

What comes out is the results of the last sentence, with each length in its own list.

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

Any idea where I'm goofing up?

1
  • 3
    Apart from the fact that you call x.split instead of i.split in your loop, your code works absolutely fine and gives the right result. Commented Mar 5, 2017 at 12:55

3 Answers 3

4

I hate thinking about these changing lists altogether. The more pythonic version is with list comprehensions:

result = [
    [len(word) for word in sentence.split(" ")]
    for sentence in sentences]
Sign up to request clarification or add additional context in comments.

Comments

1

A more concise solution would be:

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

Output:

[[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]]

Explanation:

for s in lucky will iterate through all strings in lucky. With s.split() we then split each string s into the words it is made up of. Using len(w), we then obtain the length (number of characters) for each word w in s.split().

Comments

0

The comment in your question gives you the reason why your code is failing. Here is another solution leveraging the use of map:

Python 3, you get map objects that you will have to call list on if you want to see the output as you expect.

>>> 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 will give you a list from calling 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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.