以下是按照类型或字符串获取集合的解决方法的代码示例:
方法1:使用类型进行筛选
def filter_by_type(collection, data_type):
return [item for item in collection if isinstance(item, data_type)]
# 示例用法
collection = [1, "hello", 2.5, True, "world"]
filtered_collection = filter_by_type(collection, str)
print(filtered_collection) # 输出:["hello", "world"]
方法2:使用字符串进行筛选
def filter_by_string(collection, search_string):
return [item for item in collection if search_string in str(item)]
# 示例用法
collection = [1, "hello", 2.5, True, "world"]
filtered_collection = filter_by_string(collection, "o")
print(filtered_collection) # 输出:["hello", True, "world"]
以上代码示例中,filter_by_type
函数接受一个集合和一个数据类型作为参数,使用isinstance
函数检查集合中的每个元素是否为指定的数据类型,并返回匹配的元素列表。
filter_by_string
函数接受一个集合和一个字符串作为参数,使用in
运算符检查集合中的每个元素是否包含指定的字符串,并返回匹配的元素列表。
可以根据具体需求选择使用哪种方法来获取集合。