python - 具有通用理解返回类型的函数取决于输入参数?
问题描述
假设我有一个函数可以转换字符串集合中的字符,例如 -
from typing import Collection
def replace_in_collection(input_collection: Collection[str]) -> Collection[str]:
return [x.replace('a', 'b') for x in input_collection]
如何以通用方式创建此函数,以便它返回与输入类型相同的集合类型(不仅仅是上面函数示例中的列表)。
所以我想要的是具有以下行为的东西:
my_set = {'ab','ac'}
my_set_result = replace_in_collection(my_set)
type(my_set_result ) # --> set
my_list = ['ab','ac']
my_list_result = replace_in_collection(my_list)
type(my_list_result) # --> list
有没有办法在不使用单独类型检查的情况下通过理解来创建它?
解决方案
假设所有类型的集合都接受 iterable 作为__init__
参数,那应该可以工作:
def replace_in_collection(input_collection):
collection_type = type(input_collection)
return collection_type(x.replace('a', 'b') for x in input_collection)
它确实适用set
于list
和tuple
。
正如 Chris Rands 所指出的,您可能应该检查您的输入是否属于受支持的类型:
if not isinstance(input_collection, (set, list, tuple)): # add other types if needed
raise TypeError(f"input_collection must be of type set, list or tuple, not {type(input_collection).__name__}")
推荐阅读
- php - 搜索城市内及其周边半径范围内的地点
- c++ - 在 Visual Studio 2017 中通过 CMake 使用 boost asio tcp
- python - 如何从 Python 3 的函数中更新全局变量?
- python - Docker - 将 Cassandra 容器与另一个容器链接
- php - 在 Woocommerce 3+ 上通过 PHP 更改产品可见性
- c++ - 接口“org.freedesktop.DBus.ObjectManager”上带有签名“”的方法“GetManagedObjects”不存在
- php - Google-calendar-events:无法使用 cron 或 function.php 获取日历事件
- javascript - gpu十进制精度
- python - 熊猫合并和连接
- java - 使用 Java 客户端调用启用 SSL 的肥皂 Web 服务时出错