Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无缝处理iterable和non iterable_Python_Iterable - Fatal编程技术网

Python 无缝处理iterable和non iterable

Python 无缝处理iterable和non iterable,python,iterable,Python,Iterable,你能告诉我如何优化下面的代码吗 def f(y, list_or_elem): if getattr(list_or_elem, '__iter__'): y = max(y, *list_or_elem) else: y = max(y, list_or_elem) 最好的优化方法是避免将“列表或单个元素”作为参数这样的愚蠢行为。但是,如果您坚持,最好使用try/except尽快删除异常,并确保可以: try: iter(list_or_elem) except Ty

你能告诉我如何优化下面的代码吗

def f(y, list_or_elem):
  if getattr(list_or_elem, '__iter__'):
    y = max(y, *list_or_elem)
  else:
    y = max(y, list_or_elem)

最好的优化方法是避免将“列表或单个元素”作为参数这样的愚蠢行为。但是,如果您坚持,最好使用try/except尽快删除异常,并确保可以:

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

如果你愿意在你的代码中添加展平函数(有一个很好的函数),它基本上可以获取一个列表,一个列表。。。把它放在一个单子上,你可以这样做

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

这里有类似的答案:ps:如果你这样做,添加使用该页面上指定的iter_展平方法不要忘记字符串也是可编辑的,因此
f(“xxx”,“abz”)
将返回“z”,这可能不是你想要的。再想一想,你的函数不会返回任何东西-它将结果分配给y,这是函数的本地属性。不管你通过什么论点,它都不会起作用。