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

Dave Angel davea at ieee.org
Wed May 12 20:26:00 CEST 2010


Su Chu wrote:
> 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.
>
>   
What's wrong with a loop?
> I'm at a loss, if you could help I'd really appreciate it!
>
>   
If this homework has a requirement that says don't use a loop, or don't 
use Python 3, or don't get the answer from the internet, how about 
saying so?

To see if something is in a list, use:
      if x in list3

To combine two lists, use zip()

To get more help, post some code that you've actually tried, and tell us 
why you think it's wrong.  Then we can help fix it, rather than just 
solving the homework directly.

DaveA


More information about the Tutor mailing list