Tuesday, July 30, 2013

List Comprehension Use Case

Problem : 

We have a list of  key , value pair and we just need to sum up the value part of the list. One way in languages like C# or Java was to loop through the whole loop and sum up the value part of the KeyValue object.


    class KeyValue():
    def __init__(self,key,value):
    self.key = key
        self.value = value
        def __unicode__(self):
        return self.key+"~"self.value
So typical C# or Java code for the key value object mentioned above will look like -

    def sum_up_list():
    # Lets create List
    key_value_list = []
    # What if to the sum the list
    sum_of_value = sum([x.value for x in key_value_list])  ----------One line code

       foreach obj in key_value_list {sum = sum + obj.value }; -----Same effect using loop in C#

And we are good to go

No comments:

Post a Comment