无缝处理可迭代和不可迭代
您能告诉我如何优化以下代码吗?
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)
Could you let me know how I can optimize the following code?
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好的优化是避免将“列表或单个元素”作为参数这样的愚蠢行为。但是,如果您坚持,最好使用 try/ except 尽快删除异常并确保可迭代:
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:
如果您愿意在代码中添加展平功能(有一个很好的 这里)基本上可以获取列表列表的列表...并将其简化为单个列表,您可以执行类似的操作
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