0

A sample loop below which finds a word (case-insensitive) for each list.

Question: can we do this with loop comprehension?

from __future__ import print_function

book1 = ['The', 'family', 'of', 'Dashwood', 'had', 'long', 'been']
book2 = ['let', 'it', 'divide', 'the', 'waters']
books = [book1, book2]

for book in books:
    words = ['']
    for w in book:
        words.append(w.lower())
    print(words.count('the'))
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
gammay
  • 5,957
  • 7
  • 32
  • 51
  • `words = [w.lower() for w in book]` – Jean-François Fabre Jan 19 '17 at 12:51
  • What you trying to do ? – Rahul K P Jan 19 '17 at 12:51
  • 1
    Do what in a list comprehension? What is the expected outcome? Why build lists in the first place if all you need to do is count the word `the`? – Martijn Pieters Jan 19 '17 at 12:52
  • You can't really print within list comprehension – OneCricketeer Jan 19 '17 at 12:53
  • 2
    `from itertools import chain; from collections import Counter`, `word_counts = Counter(map(str.lower, chain(book1, book2)))`, then `print(word_counts['the'])`. Much, *much* more efficient if you need counts for each of the words, not just `the`. – Martijn Pieters Jan 19 '17 at 12:53
  • Maybe the example problem is bad... but the intent behind the question is what can we and cannot do with loop comprehensions? If I have a logic as above (which has loop within loop and some additional processing) can we do this with loop comprehension for brevity? – gammay Jan 19 '17 at 13:06
  • @cricket_007 it is certainly possible to print within list comprehension. For instance i can do this `[print(book) for book in books]` – gammay Jan 19 '17 at 13:08
  • Sure, but you then have a list of all None, which is useless – OneCricketeer Jan 19 '17 at 13:23
  • And, as answered already, you can create `words` using list comprehension, you should use a for loop if you want to print it out – OneCricketeer Jan 19 '17 at 13:24
  • We can do `print([book for book in books])` or `print [book for book in books]` if we do don't want to import print_function – gammay Jan 19 '17 at 13:34
  • `words = [w.lower() for w in book]` does not really answer the question. The real question is _can the above logic be done within a single line comprehension?_ (keeping aside for the moment if there is a better way to do it or what we are trying to do). Just trying to understand limitations of loop comprehension. – gammay Jan 19 '17 at 13:37

0 Answers0