Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, best way to write a sum of two for loops

Normally I know we can do sum([func(x,x) for x in i]), but I got an if check and two for loops, so what is the most pythonic way to write the code bellow. you can assume that similarity will return a number regardless of what type you give it. You can also assume that it will really only get ints and chars.

x = 0
if isinstance(a, dict) or isinstance(a, list) or isinstance(a, tuple):
    for i in a:
        for j in b:
            x += similarity (i,j)
like image 731
EasilyBaffled Avatar asked May 07 '13 20:05

EasilyBaffled


1 Answers

Maybe something like this:

x=0
if isinstance(a,(dict,list,tuple)):
    x=sum(similarity(i,j) for i in a for j in b)

Or:

x=(sum(similarity(i,j) for i in a for j in b) if isinstance(a,(dict,list,tuple)) 
   else 0)

Or (assuming that a string, set or some other iterable type does not break your function for some reason):

try:
   x=sum(similarity(i,j) for i in a for j in b)
except TypeError:
   x=0

If you are specifically looking to test if something is iterable, you can do that this way:

from collections import Iterable
if isinstance(e, Iterable):
   ...

If there are certain iterable types you do not want, react to those:

if isinstance(e, Iterable) and not isinstance(el, str):
   # an iterable that is not a string...
like image 155
dawg Avatar answered Nov 15 '22 20:11

dawg