how can I avoid abusing lists?

Simon Forman rogue_pedro at yahoo.com
Fri Jul 7 16:54:07 EDT 2006


Thomas Nelson wrote:
> Thanks to everyone who posted.  First, I don't think my question was
> clear enough: Rob Cowie, Ant, Simon Forman, mensanator at aol.com, and Jon
> Ribbens offered solutions that don't quite work as-is, because I need
> multiple values to map to a single type.  Tim Chase and Bruno
> Destuilliers both offer very nice OOP solutions, and I think this is
> the route I will probably go.  However, for the simplest and easiest
> solution, I really like this from Peter Otten:
> inflated = [0]*5
> groups = [[0,1,3],[4],[2]]
> for value in [1,1,0,4]:
> 	inflated[value] += 1
> print [sum(inflated[i] for i in group) for group in groups]
>
> 4 lines (one more to assign the lists to name values, but that's
> minor), and intuitive.  If I had just thought of this to begin with, I
> wouldn't have bothered posting.
>
> Thanks to all for the advice.
>
> THN

I want to be sure I understand the above.

inflated is a list of counters, one for each "type code"?

groups is a list of groups of "type codes", one for each actual "type"?

The for loop simulates four calls to an "increment()" function?

The list comprehension sums all the counters that correspond to each
actual type?

so you could write:

type1, type2, type3 = groups = [[0,1,3],[4],[2]]

Is that right?


Wow, very nice.


Peace,
~Simon


It was too easy to read
 map = {0:type1, 1:type1, 2:type3, 3:type1, 4:type2}
as
 map = {0:type1, 1:type2, 2:type3, 3:type4, 4:type5}

sorry.




More information about the Python-list mailing list