Eliminate "extra" variable

Ethan Furman ethan at stoneleaf.us
Sat Dec 7 00:49:18 CET 2013


On 12/06/2013 03:38 PM, Joel Goldstick wrote:
> On Fri, Dec 6, 2013 at 2:37 PM, Igor Korot wrote:
>>
>>     def MyFunc(self, originalData):
>>           data = {}
>>           dateStrs = []
>>           for i in xrange(0, len(originalData)):
>>                 dateStr, freq, source = originalData[i]
>>                 data[str(dateStr)]  = {source: freq}
>>
>>                 # above line confuses me!
>>
>>                 dateStrs.append(dateStr)
>>          for i in xrange(0, len(dateStrs) - 1):
>>                currDateStr = str(dateStrs[i])
>>                nextDateStrs = str(dateStrs[i + 1])
>
> Python lets you iterate over a list directly, so :
>
>      for d in originalData:
>          dateStr, freq, source = d
>          data[source] = freq

You could shorten that to

        for dateStr, freq, source in originalData:

and if dateStr is already a string:

            data[dateStr] = {source: freq}

> Your code looks like you come from a c background.  Python idioms are different

Agreed.


> I'm not sure what you are trying to do in the second for loop, but I think you are trying to iterate thru a dictionary
> in a certain order, and you can't depend on the order

The second loop is iterating over the list dateStrs.

--
~Ethan~



More information about the Python-list mailing list