简体   繁体   English

返回类型取决于 Python 中的输入类型

[英]Return type dependent on input type in Python

The following function in Python can returns a list no matter if the input is a list , a numpy.array or a pandas.Series .无论输入是listnumpy.array还是pandas.Series ,Python 中的以下函数都可以返回列表。

What is the pythonic way to write it so that the output type is the same as the input type?编写它以便输出类型与输入类型相同的pythonic方法是什么?

def foo(input):
    output = []

    output.append(input[0])

    for i in range(1, len(input)-1):
        if (some condition):
            output.append(input[i])

    output.append(input[-1])

    return output

In general, you can't do this without making a lot of assumptions about what the input is .一般来说,如果不对输入什么做很多假设,你就无法做到这一点

The first step would be to make sure that output is the right type, not a list.第一步是确保output是正确的类型,而不是列表。

output = type(self)()

However, this assumes that whatever type your input is, you can create an instance by calling it with no arguments.但是,这假设无论您的输入是什么类型,您都可以通过不带参数调用它来创建一个实例。

Next, you have to restrict yourself to operations on output that are supported by all expected inputs.接下来,您必须限制自己对所有预期输入都支持的output进行操作。 Not all iterables support an append method ( set , for instance, uses add , not append ), and not all iterables support __getitem__ (a generator, for instance).并非所有迭代器都支持append方法(例如set使用add ,而不是append ),并且并非所有迭代器都支持__getitem__ (例如生成器)。 This means that you can't generalize your function too much;这意味着你不能过多地概括你的函数; you always have to keep in mind which types of input you will support.您必须始终牢记您将支持哪些类型的输入。

Alternatively, if the set of types you want to support can create an instance from a list, you can let output = [] stand, but convert it just before returning:或者,如果您要支持的类型集可以从列表创建实例,您可以让output = []保持不变,但在返回之前转换它:

return type(self)(output)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM