[Tutor] Find Elements in List That Equal A Specific Value

Su Chu sushikyc at gmail.com
Wed May 12 19:58:45 CEST 2010


Hi there,

I am new to Python. I am attempting to either define a "which" statement or
to find a method that already exists to do this sort of operation.

My problem is as follows:
I have three lists, one with unique values (list 1), one a sequence of
values that are not necessarily unique (list2), and a shorter list with the
unique values of list 2 (list 3). List 1 and List 2 are of equal lengths.


An example:
list1 = [ 1, 2, 3, 4, 5, 6 ]
list2 = [ 2, 2, 2, 5, 6, 6 ]
list3 = [2, 5, 6]

What I would like to do is find and sum the elements of list 1 given its
corresponding element in list 2 is equal to some element in list 3.

For example,
the sum of the values in list1 given list2[i]==2
would be 1 + 2 + 3 = 6.
the sum of the values in list1 given list2[i]==5
would be 4
the sum of the values in list1 given list2[i]==6
would be 5 + 6 = 11

and so on. Obtaining these values, I'd like to store them in a vector.

This seems pretty simple if a 'which' statement exists e.g. (which values in
list 1 == list3[k], and looping through k), but I can't find one. To write
one seems to require a loop.

I'm at a loss, if you could help I'd really appreciate it!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100512/c88cf0a8/attachment-0001.html>


More information about the Tutor mailing list