代码之家  ›  专栏  ›  技术社区  ›  Paul Jurczak

这两个Python函数可以被一个接受列表或元组参数的泛型函数替换吗?

  •  1
  • Paul Jurczak  · 技术社区  · 10 月前

    这两个Python函数可以:

    def negativeList(a):
      return [-e for e in a]
    
    def negativeTuple(a):
      return tuple(-e for e in a)
    

    被等效的单一泛型函数所取代 negative(a) ?

    2 回复  |  直到 10 月前
        1
  •  5
  •   Komol Kunty Rajib    10 月前

    您可以使用 isinstance 函数检查输入的类型,然后返回相应的类型。

    def negative_sequence(a):
        if isinstance(a, list):
            return [-e for e in a]
        elif isinstance(a, tuple):
            return tuple(-e for e in a)
        else:
            raise TypeError("Input must be a list or a tuple")
    
    # Example usage:
    print(negative_sequence([1, 2, 3]))  # Output: [-1, -2, -3]
    print(negative_sequence((1, 2, 3)))  # Output: (-1, -2, -3)
    
        2
  •  4
  •   Tarik    10 月前

    您可以在运行时确定类型

    def negative(a):
        return type(a)((-e for e in a))
    
        3
  •  0
  •   Derek Roberts    10 月前

    所以我们也可以使用 Iterable 类使其更健壮

    from collections.abc import Iterable
    import numpy as np
    
    
    def negative(a):
        if isinstance(a, Iterable):
            result = (-e for e in a)
            if isinstance(a, list):
                return list(result)
            elif isinstance(a, tuple):
                return tuple(result)
            elif isinstance(a, np.ndarray):
                return np.negative(a)
            else:
                raise TypeError("Not supported iterable type.")
        else:
            raise TypeError("Interables only.")