From: Anthony Papillion on 10 Jun 2010 16:47 Someone helped me with some code yesterday and I'm trying to understand it. The way they wrote it was subjects = (info[2] for info in items) Perhaps I'm not truly understanding what this does. Does this do anything different than if I wrote for info[2] in items subject = info[2] Thanks! Anthony
From: Emile van Sebille on 10 Jun 2010 17:19 On 6/10/2010 1:47 PM Anthony Papillion said... > Someone helped me with some code yesterday and I'm trying to > understand it. The way they wrote it was > > subjects = (info[2] for info in items) > > Perhaps I'm not truly understanding what this does. Does this do > anything different than if I wrote > > for info[2] in items > subject = info[2] > more like: result = [] for info in items: result.append(info[2]) subjects =iter(result) Emile
From: Thomas Jollans on 10 Jun 2010 17:22 On 06/10/2010 10:47 PM, Anthony Papillion wrote: > Someone helped me with some code yesterday and I'm trying to > understand it. The way they wrote it was > > subjects = (info[2] for info in items) This is a generator expression, and it creates a generator object. If you loop over it (subjects), you will get all the subjects (or whatever info[2] is), one by one. > > Perhaps I'm not truly understanding what this does. Does this do > anything different than if I wrote > > for info[2] in items > subject = info[2] These two snippets do the same thing: # No. 1. subjects = (info[2] for info in items) for subject in subjects: print (subject) # No. 2. for info in items: subject = info[2] print (subject) However, you could also pass the subjects variable to another function and have it iterate over them - that's something that the simple loop can't do just like that. > > Thanks! > Anthony
From: Anthony Papillion on 10 Jun 2010 18:13 Thank you Emile and Thomas! I appreciate the help. MUCH clearer now.
From: Martin on 10 Jun 2010 18:27 On Jun 10, 11:13 pm, Anthony Papillion <papill...(a)gmail.com> wrote: > Thank you Emile and Thomas! I appreciate the help. MUCH clearer now. Also at a guess I think perhaps you wrote the syntax slightly wrong (square brackets)...you might want to look up "list comprehension" Martin
|
Next
|
Last
Pages: 1 2 Prev: Decimal problem Next: MySQLdb problems with named pipe connection on Windows 7? |