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

Lie Ryan lie.1296 at gmail.com
Wed May 12 21:28:12 CEST 2010


On 05/13/10 03:58, 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.

your proposed 'which' statement, had they existed, is a kind of loop, so
I'm wondering why you want to avoid loops.

>>> [sum(a for a, b in zip(list1, list2) if b == n) for n in list3]
[6, 4, 11]



More information about the Tutor mailing list