473,406 Members | 2,273 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Using reverse iteration to clean up a list

I have list of lists of the following form

L=[['A', 100], ['B', 300], ['A', 400], ['B', -100]]

I want to aggregate these lists, i.e. to reduce L to
L=[['A', 500], ['B', 200]] #500 = 100+400, 200=300-100

Here's how I have done it:
L.sort()
for i in range(len(L),0,-1):
if L[i-1][0]=L[i][0]:
L[i-1][2] += L[i][2]
del L[i]

Is there a simpler way to do this using the new reverse iteration
facility in Python 2.4?

Thomas Philips

Jul 18 '05 #1
6 1879
tk****@hotmail.com writes:
I have list of lists of the following form

L=[['A', 100], ['B', 300], ['A', 400], ['B', -100]]

I want to aggregate these lists, i.e. to reduce L to
L=[['A', 500], ['B', 200]] #500 = 100+400, 200=300-100


How about:

v = {}
for name,val in L:
v[name] = v.get(name, 0) + val
L = v.items()
Jul 18 '05 #2

Paul Rubin wrote:
tk****@hotmail.com writes:
I have list of lists of the following form

L=[['A', 100], ['B', 300], ['A', 400], ['B', -100]]

I want to aggregate these lists, i.e. to reduce L to
L=[['A', 500], ['B', 200]] #500 = 100+400, 200=300-100


How about:

v = {}
for name,val in L:
v[name] = v.get(name, 0) + val
L = v.items()


Followed by L.sort() if the OP really needs his list sorted.
Alternatively, he may prefer to leave it in a dict; in fact, if he had
been using a dict all along and maintaining it on the fly by "v[name]
= v.get(name, 0) + val", he wouldn't need to batch-fix his data
structure now.

tkpmep, how did you get this list of lists with duplicate keys and
additive values? What do you want to do with it next?

Jul 18 '05 #3
Well, I'm not sure if this is what you want, but you could use a
dictionary:
d={}
for i,e in L: if d.has_key(i):
d[i] += e
else:
d[i] = e

d {'A': 500, 'B': 200}


Jul 18 '05 #4
tk****@hotmail.com wrote:
L=[['A', 100], ['B', 300], ['A', 400], ['B', -100]]

I want to aggregate these lists, i.e. to reduce L to
L=[['A', 500], ['B', 200]] #500 = 100+400, 200=300-100


"""
from itertools import groupby
from operator import itemgetter

[(key, sum(item[1] for item in sublist))
for key, sublist
in groupby(sorted(L, key=itemgetter(0)), itemgetter(0))]
"""

OK, strictly speaking that will get you a list of tuples
instead of a list of lists, but that's easy enough to fix
if you insist on a list of lists. Tuples are generally used
for heterogeneous fixed-length sequences.
--
Michael Hoffman
Jul 18 '05 #5
Thank you all so much for the generous dollop of help: the dictionary
suggestion is particularly helpful. The problem arises as follows: A
software application stores the securities held in a portfolio in a
..csv file, one row per security, with three colulmns.

The first has a security identifier or descriptor (such as a ticker)
the second has a single letter that identifies the type of the
identifier (T for ticker, C for cusip etc.) and the third has the
number of shares. A typical line looks like this:

IBM, T, 500

I need to read in one or more portfolios and aggregate their holdings.
To do so, I read in the portfolios using the csv package, convert each
line to a list and then append it to a list of lists. Eventually the
list of lists contains all the securities, and can then be sorted and
aggregated.

I suppose I could convert it instead to a dictionary, and the most
natural key would be the first two items, i.e. a portfolio containing
just 500 shares of IBM ought to be represented as
{("IBM", "T") : 500 }

How can I translate the data I read in using csv.reader into a
dictionary?

Thomas Philips

Jul 18 '05 #6
tk****@hotmail.com wrote:
Thank you all so much for the generous dollop of help: the dictionary
suggestion is particularly helpful. The problem arises as follows: A
software application stores the securities held in a portfolio in a
.csv file, one row per security, with three colulmns.

The first has a security identifier or descriptor (such as a ticker)
the second has a single letter that identifies the type of the
identifier (T for ticker, C for cusip etc.) and the third has the
number of shares. A typical line looks like this:

IBM, T, 500

I need to read in one or more portfolios and aggregate their holdings.
To do so, I read in the portfolios using the csv package, convert each
line to a list and then append it to a list of lists. Eventually the
list of lists contains all the securities, and can then be sorted and
aggregated.

I suppose I could convert it instead to a dictionary, and the most
natural key would be the first two items, i.e. a portfolio containing
just 500 shares of IBM ought to be represented as
{("IBM", "T") : 500 }

How can I translate the data I read in using csv.reader into a
dictionary?


portfolio = {}

for row in csv.reader(infile):
key = tuple(row[:2])

portfolio[key] = portfolio.get(key, 0) + int(row[2])

You could also do a groupby solution with
itemgetter(slice(0, 2))--thanks to Steven Bethard for recently
pointing out the possibility here of doing that. I'd go with the
dict for this application though.
--
Michael Hoffman
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
by: Raymond Hettinger | last post by:
Here is a discussion draft of a potential PEP. The ideas grew out of the discussion on pep-284. Comments are invited. Dart throwing is optional. Raymond Hettinger ...
59
by: Raymond Hettinger | last post by:
Please comment on the new PEP for reverse iteration methods. Basically, the idea looks like this: for i in xrange(10).iter_backwards(): # 9,8,7,6,5,4,3,2,1,0 <do something with i> The...
31
by: Raymond Hettinger | last post by:
Based on your extensive feedback, PEP 322 has been completely revised. The response was strongly positive, but almost everyone preferred having a function instead of multiple object methods. The...
14
by: Raymond Hettinger | last post by:
Based on the feedback here on comp.lang.python, the pep has been updated: www.python.org/peps/pep-0322.html The key changes are: * reversed() is being preferred to ireverse() as the best...
8
by: rh0dium | last post by:
Hi all, I have a dict which looks like this.. dict={'130nm': {'umc': }, '180nm': {'chartered': , 'tsmc': }, '250nm': {'umc': , 'tsmc': } }
10
by: AZRebelCowgirl73 | last post by:
This is what I have so far: My program! import java.util.*; import java.lang.*; import java.io.*; import ch06.lists.*; public class UIandDB {
4
by: John A Grandy | last post by:
Is there a performance difference between forward iteration and reverse iteration through a List<string? for ( i = 0; i < myList.Count; i++ ) { // do work, such as forward iterate through a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.