我想知道为什么我无法通过谷歌搜索找到任何解决方案: 我想编写一个python函数,它可以接受单个对象或任何相同类型的集合。我的想法是,如果参数是单个实例,则在参数周围包装一个列表,如下所示:
def postprocess(results):
""" An arbitrary function that takes a list or single object
and behaves smart depending on that. """
if not is_collection(results): # <-- How to implement this??
results = [results]
for result in results:
# do processing magic
print(result)
# to be called like one of those:
postprocess(result1) # single object
postprocess([result1, result2]) # a list
postprocess((result1, result2)) # a tuple
实现is_collection()
的最好/最有效的方法是什么? (如果result
本身是可迭代的类型,可能会带来问题吗?
我可以做if type(results) is not list:
,但我明确地希望不仅允许list
允许任何种类的可迭代集合。