-3
s = 'coffee coke tea lemonade milk sprite'

{ c:s.count(c) for c in ''.join([ w[1:] for w in s.split() 
  if 'e' not in w[-3:-1] and 'o' in w[:4] ]) }


# (’’.join([ w[1:] for w in s.split())

how does the w work is it run through the s.split() that has a total of 6 elements? or through each letter in the separated strings(e.g. 'coffee' etc. )? Why is the answer for this comprehension {'o': 3, 'k': 2, 'e': 7, 'm': 2, 'n': 1, 'a': 2, 'd': 1}.

I understand why it is a dictionary but the variable c and w are confusing to me, currently I think that the value for those variable are changing as the loop goes but I don't understand how the other code effects how they change.

Phil L
  • 11
  • 1
  • 3
    Possible duplicate of [Explanation of how nested list comprehension works?](https://stackoverflow.com/questions/20639180/explanation-of-how-nested-list-comprehension-works) – Jaydip Rakholiya Sep 16 '18 at 20:24

1 Answers1

0

If you want to analyze how something works, take it apart:

s = 'coffee coke tea lemonade milk sprite'

d = { c:s.count(c) for c in ''.join([ w[1:] for w in s.split() 
  if 'e' not in w[-3:-1] and 'o' in w[:4] ]) }

print(d)

Output:

{'o': 3, 'k': 2, 'e': 7, 'm': 2, 'n': 1, 'a': 2, 'd': 1}

Lets take the parts as well:

print(list(w for w in s.split()))
print(list(w for w in s.split() if 'e' not in w[-3:-1] and 'o' in w[:4] ))
print(''.join([ w[1:] for w in s.split() if 'e' not in w[-3:-1] and 'o' in w[:4] ]))

Output:

['coffee', 'coke', 'tea', 'lemonade', 'milk', 'sprite']
['coke', 'lemonade']
okeemonade

So: w takes all values from s.split(), which are 'coffee' 'coke' 'tea' 'lemonade' 'milk' 'sprite' but not all vaues are used, only those that pass if 'e' not in w[-3:-1] and 'o' in w[:4] with true AND then the part without the first character is fed to the next part of the comprehension.

The first part iterates over all characters in 'okeemonade' and counts how often this letter occures inside s.

Done.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69