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

Luke Paireepinart rabidpoobear at gmail.com
Wed May 12 22:10:56 CEST 2010


On Wed, May 12, 2010 at 1:22 PM, bob gailer <bgailer at gmail.com> wrote:
> On 5/12/2010 1:58 PM, Su Chu wrote:
>>
>> 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.
>>
>> 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.
>>
> result = []
> for n in list3:
>  result.append(sum(list1[x] for x in range(len(list1)) if list2[x] = n)
>
bob,
your parenthesis are unbalanced and you put an assignment instead of a
comparison...

I'd probably do this with a dictionary.
d = {}
for i, val in enumerate(list1):
    d[list2[i]] = val + d.get(list2[i], 0) # or whatever the default
get code is.


More information about the Tutor mailing list