Eliminate "extra" variable

Joel Goldstick joel.goldstick at gmail.com
Fri Dec 6 18:38:37 EST 2013


On Fri, Dec 6, 2013 at 2:37 PM, Igor Korot <ikorot01 at gmail.com> wrote:

> Hi, ALL,
> I have following code:
>
> 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

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

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

>
> It seems very strange that I need the dateStrs list just for the
> purpose of looping thru the dictionary keys.
> Can I get rid of the "dateStrs" variable?
>
> Thank you.
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Joel Goldstick
http://joelgoldstick.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20131206/d9d63ff7/attachment.html>


More information about the Python-list mailing list