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)
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With