I'm used to seeing For Loops in this format:
for number in l:
sum = sum + number
I was browsing some forums and came across this piece of code:
count_chars = ".arPZ"
string = "Phillip S. is doing a really good job."
counts = tuple(string.count(d) for(d) in count_chars)
print counts
I'm not sure if that is really a For loop, so I decided to rewrite it in a way that I understood:
tuple(
for(d) in count_chars:
string.count(d))
Needless to say, it failed lol. So can someone explain what is going on, and explain the folly of my logic? Thanks!!
-
This is called a generator expression. I am sure someone will post a more expert answer than I will write.anon582847382– anon5828473822014年04月06日 17:07:20 +00:00Commented Apr 6, 2014 at 17:07
-
Thanks for getting me in the right direction. I had no idea what a generator expression was!dyao– dyao2014年04月06日 17:10:58 +00:00Commented Apr 6, 2014 at 17:10
-
Here is a short video about list comprehensions and it's siblings, including generator expressions.Gareth Latty– Gareth Latty2014年04月06日 17:13:29 +00:00Commented Apr 6, 2014 at 17:13
-
@user3386440 Nobody posted anything (correct) so I wrote something up, see below.anon582847382– anon5828473822014年04月06日 17:14:42 +00:00Commented Apr 6, 2014 at 17:14
-
possible duplicate of Python `for` syntax: block code vs single line generator expressionsFfisegydd– Ffisegydd2014年04月06日 17:23:56 +00:00Commented Apr 6, 2014 at 17:23
1 Answer 1
It's not quite a for loop as such, but a generator expression. What it basically does is return an iterator where each element is the amount of time every character in count_chars occurs in d. It then adds all of these elements into a tuple.
It is (roughly) equivalent to:
counts = []
for d in count_chars:
counts.append(string.count(d))
counts = tuple(counts)
2 Comments
counts. For every element in count_chars, count how many times it is in string and add that number to the list counts. Convert counts to a tuple.append on my own but I think I got the rest of it. Assume I didn't want it to appear on a list ie: (2,2,1,1,0). Instead I want it to be be simply print out. I will show you want I mean in the OP.