Lorn wrote:
> I'm trying to figure out a way to create dynamic lists or possibly
> antother solution for the following problem. I have multiple lines in a
> text file (every line is the same format) that are iterated over and
> which need to be compared to previous lines in the file in order to
> perform some simple math. Each line contains 3 fileds: a descriptor and
> two integers. Here is an example:
> 
> rose, 1, 500
> lilac, 1, 300
> lilly, 1, 400
> rose, 0, 100

Do you have to maintain a list or just the current value?
Also I did not find it clear why you have to compare with previous line?

Anyway, I think dictionnary may be useful there:


  >>> input = """rose, 1, 500
  ... lilac, 1, 300
  ... lilly, 1, 400
  ... rose, 0, 100"""
  >>>
  >>> entries = [l.split(',') for l in input.split('\n')]
  >>>
  >>> d = {}
  >>> for k, op, n in entries:
  ...     if int(op) == 1:
  ...         d[k] = d.get(k, 0) + int(n)
  ...     else:
  ...         d[k] = d.get(k, 0) - int(n)
  ...
  >>> print d
  {'rose': 400, 'lilly': 400, 'lilac': 300}
  >>>


That may not be what you want but there may be some things for you to use.
And you can of course keep the full list of operation in d.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to