Custom Search

Wednesday, January 9, 2013

How to find all numbers divisible by 2 and 3 from a list using comprehension


With list comprehension
 ===================
>>>
>>> numbers = [1, 2, 3, 5, 8, 13, 51, 72]
>>>
>>>
>>>
>>> [ [num for num in numbers if num%devi == 0] for devi in [2, 3] ]
[[2, 8, 72], [3, 51, 72]]
>>>
>>>

Without list comprehension
=====================
>>> result = []
>>> for devi in [2,3]:
...     res = []
...     for num in numbers:
...             if num%devi == 0:
...                     res.append(num)
...     result.append(res)
...
>>>
>>>
>>>
>>> result
[[2, 8, 72], [3, 51, 72]]
>>>
>>>
>>>

No comments:

Post a Comment