Search for mapping solution
Achim Domma
domma at procoders.net
Sun Jul 6 17:29:38 EDT 2003
"Markus Joschko" <jocsch at phreaker.net> wrote in message
news:bea0fe$2otcq$1 at ID-47851.news.dfncis.de...
> thanks it works. But maybe I can complicate the example a little bit
> (because in real world it's more complicated):
>
> What if I every list in lines has 20 or more entries and I have only the
> index number to access the name, e.g.
>
> lines = [['elem1','elem2','fred','elem3',.......;'elem
> 17','333','elem18','0.10'],[...],[...]]
I'm not sure, if I understand you right, but I think you could do it like
this:
nameIndex = 3
costs = {}
for item in lines:
name = item[nameIndex]
costs[name] = costs.setdefault(name,0)+float(item[-1])
print costs
This assumes, that the price is always on the last position. Depending on
your requirements there are differnt ways to write it more clearly:
nameIndex = 3
costs = {}
for name,price in [ (x[nameIndex],x[-1]) for x in lines) ]:
costs[name] = costs.setdefault(name,0)+float(price)
Or something like that:
def priceIter(lines,nameIndex):
for x in lines: yield x[nameIndex],x[-1]
costs = {}
for name,price in priceIter(lines,3):
costs[name] = costs.setdefault(name,0)+float(price)
It depends on your situation, what's the best solution for you. Depending on
your control flow it might be convenient do something like this:
def createLinesIter(nameIndex,priceIndex):
def priceIter(lines,nameIdx=nameIndex,priceIdx=priceIndex):
for x in lines: yield x[nameIdx],x[priceIdx]
Now you could create special Iterators for your lists an pass them around:
TypA_Iter = createLinesIter(0,-1)
TypB_Iter = creaetLinesIter(3,7)
now you can pass these funtions around with your matching lines list:
def processLines(lines,linesIter):
costs = {}
for name,price in linesIter(lines):
costs[name] = costs.setdefault(name,0)+float(price)
return costs
And now for your first list:
lines = ....
costs = processLines(lines,TypA_Iter)
The examples are written from head, so there might be some typos. But they
should give you a hint on what's possible in python.
regards,
Achim
More information about the Python-list
mailing list