Comprehension is an elegant way to define and create
lists/Dictionaries/sets in Python.
Modifying the above comprehension so that the resulting list does not include (0,0,0) we get:
Dictionary comprehensions are used to create dictionaries. Almost like the above two types. These are mainly used when we have a relation between the 'key' and the 'value' and the same relation is repeated throughout the dictionary.
List comprehension
>>> a=[1,2,3,4]
>>> b=[x+1 for x in a]
>>> print b
[2, 3, 4, 5]
>>> b=[x+1 for x in a]
>>> print b
[2, 3, 4, 5]
This can be used as a substitute for map function.
It can even have conditional statements for eg:
>>> a=range(50)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
>>> b=[x for x in a if ((x%8)==0 and (x%3)==0)]
>>> b
[0, 24, 48]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
>>> b=[x for x in a if ((x%8)==0 and (x%3)==0)]
>>> b
[0, 24, 48]
This piece of code prints all the nos between 0 and 50 thos are divisible by both 8 and 3.
This is how comprehensions make python more attractive!
Set comrehension
Set comprehension also works like list comprehension with an exception that it does not have any duplicate elements. Further there is a slight difference in the syntax also.
This is how we can use set comprehensions:
>>>S= {-4, -2, 1, 2, 5, 0}
Write a triple comprehension those value is a list of all three element tuples (i,j,k) such that i,j,k are elements of S whose sum is zero.
>>>S = {-4, -2, 1, 2, 5, 0}
>>>zero_sum_list ={(x,y,z) for x in S for y in S for z in S if (x+y+z)==0}
This is an example for triple comprehension.
>>>zero_sum_list ={(x,y,z) for x in S for y in S for z in S if (x+y+z)==0}
This is an example for triple comprehension.
Modifying the above comprehension so that the resulting list does not include (0,0,0) we get:
>>>excluded_zero_sum_list ={(x,y,z) for x in s for y in s for z in s if ((x+y+z)==0} and (x or y or z)!=0)]
Dictionary comprehension
Dictionary comprehensions are used to create dictionaries. Almost like the above two types. These are mainly used when we have a relation between the 'key' and the 'value' and the same relation is repeated throughout the dictionary.
Here is a n example:
Using `range', write a dictionary comprehension: the keys of the dictionary are values from 0 to 4 and the value corresponding to each key is the square of the key.
>>>square_dict ={x:x*x for x in range(5)]
>>>square_dict ={x:x*x for x in range(5)]
>>> square_dict
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}






0 comments:
Post a Comment