Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #61204 > unrolled thread

Re: Eliminate "extra" variable

Started byTim Chase <python.list@tim.thechases.com>
First post2013-12-06 18:37 -0600
Last post2013-12-06 18:37 -0600
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Eliminate "extra" variable Tim Chase <python.list@tim.thechases.com> - 2013-12-06 18:37 -0600

#61204 — Re: Eliminate "extra" variable

FromTim Chase <python.list@tim.thechases.com>
Date2013-12-06 18:37 -0600
SubjectRe: Eliminate "extra" variable
Message-ID<mailman.3681.1386376572.18130.python-list@python.org>
On 2013-12-06 11:37, Igor Korot wrote:
> def MyFunc(self, originalData):
>      data = {}
>      for i in xrange(0, len(originalData)):
>            dateStr, freq, source = originalData[i]
>            data[str(dateStr)]  = {source: freq}

this can be more cleanly/pythonically written as

  def my_func(self, original_data):
    for date, freq, source in original_data
      data[str(date)] = {source: freq}

or even just

    data = dict(
      (str(date), {source: freq})
      for date, freq, source in original_data
      )

You're calling it a "dateStr", which suggests that it's already a
string, so I'm not sure why you're str()'ing it.  So I'd either just
call it "date", or skip the str(date) bit if it's already a string.
That said, do you even need to convert it to a string (as
datetime.date objects can be used as keys in dictionaries)?

>     for i in xrange(0, len(dateStrs) - 1):
>           currDateStr = str(dateStrs[i])
>           nextDateStrs = str(dateStrs[i + 1])
> 
> 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?

Your code isn't actually using the data-dict at this point.  If you
were doing something with it, it might help to know what you want to
do.

Well, you can iterate over the original data, zipping them together:

  for (cur, _, _), (next, _, _) in zip(
      original_data[:-1],
      original_data[1:]
      ):
    do_something(cur, next)

If your purpose for the "data" dict is to merely look up stats from
the next one, the whole batch of your original code can be replaced
with:

  for (
        (cur_dt, cur_freq, cur_source),
        (next_dt, next_freq, next_source)
        ) in zip(original_data[:-1], original_data[1:]):
    # might need to do str(cur_dt) and str(next_dt) instead?
    do_things_with(cur_dt, cur_freq, cur_source,
      next_dt, next_freq, next_source)

That eliminates the dict *and* the extra variable name. :-)

-tkc



[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web