开发者

Handle iterable and non-iterable seamlessly

开发者 https://www.devze.com 2022-12-30 07:15 出处:网络
Could you let me know how I can optimize the following code? def f(y, list_or_elem): 开发者_JS百科if getattr(list_or_elem, \'__iter__\'):

Could you let me know how I can optimize the following code?

def f(y, list_or_elem):
  开发者_JS百科if getattr(list_or_elem, '__iter__'):
    y = max(y, *list_or_elem)
  else:
    y = max(y, list_or_elem)


The best optimization of all would be to avoid such silliness as taking "either a list or a single element" as an argument. But, if you insist, it's better to use a try/except to remove the anomaly ASAP and make what's sure to be an iterable:

try: iter(list_or_elem)
except TypeError: iterable = [list_or_elem]
else: iterable = list_or_elem
y = max(y, *iterable)


if you are willing to have add flatten function in your code (theres a good one here) which can basically take a list of lists of lists of... and bring it down to a single list, you can do something like

y = max(flatten([y, list_or_elem]))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号