Hi,

I have a list which contains strings in each value. I want the word count of each string and then I will have to find out the string with minimum word count and max. word count in that list. Help is much appreciated.

Can you assume that each word is separated by a space (one and only one), and that there are no leading and trailing spaces? If so, let's say your list of strings is "list-1". Then you could make a list of word counts as: list-2=[i.count(" ")+1 for i in list-1]
Then the max word count is: max(list-2),
and the string in list-1 with that count is: list-1[list-2.index(max(list-2))]

There are several ways to do this, including dictionaries, loops, etc.
A simple solution would be to use a DSU (decorate, sort, undecorate).

Let's assume you have the following list:

my_list = ["I like apples", "Remember to eat your greens", Drink plenty of water"]

We can use the split() method on every string in my_list to get a list of the words composing it:

"I like apples".split()

Will produce:

["I", "like", "apples"]

Now we can call the built in len() method on the result:

len(["I", "like", "apples"])

Will yield:

3

Which is exactly the amount of words in that sentence.

Now that we know how to count the amount of words in each item, we can create nice pairs (tuples) of (amount of words in item, item):

(len(item.split()), item)

Once you have all pairs in a separate list, and since Python sorts tuples based on the value of their first item (second if first is identical and so forth), you can just call max(seperate_list) and min(seperate_list) and you'll have your answers.

We basically decorated each item in the original list with the "key" we wanted to sort by. We could have also used a DSU pattern to sort my_list by any other criteria we wished (e.g. has the word "rice" in it, has an odd number of letters, etc.)

Good luck!

commented: good idea +14

Hi, the replies were really helpful..thanks for that !!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.