当前位置: 首页 > 编程笔记 >

python 内置函数filter

梁骞仕
2023-03-14
本文向大家介绍python 内置函数filter,包括了python 内置函数filter的使用技巧和注意事项,需要的朋友参考一下

python 内置函数filter

class filter(object):
 """
 filter(function or None, iterable) --> filter object
 
 Return an iterator yielding those items of iterable for which function(item)
 is true. If function is None, return the items that are true.
 """

filter(func,iterator)

    func:自定义或匿名函数中所得值是布尔值,true将保留函数所取到的值,false则取反。
    iterator:可迭代对象。

例:

     过滤列表['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']
     只要含有text字符串及将其取出 or 取反。

s.rfind'text'+1

     Python3中 rfind() 返回字符串最后一次出现的位置,如果没有匹配项则返回-1。
     数字中0是false,0以上的整数都是true,所以s.rfind'text'后会有+1,没找到字符及-1+1=0.

# Filter

li = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']

# 默认保留函数所取到的值
print(list(filter(lambda s: s.rfind('text') + 1, li)))
# 取反,下三个例子是一样的
print(list(filter(lambda s: not s.rfind('text') + 1, li)))

# Noe 自定义函数

l1 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']


def distinguish(l):
 nl = []
 for s in l:
  if s.rfind("text") + 1:
   nl.append(s)
 return nl


print(distinguish(l1))

# Two 自定义高阶函数

l2 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']


def f(s):
 return s.rfind('text') + 1


def distinguish(func, array):
 nl = []
 for s in array:
  if func(s):
   nl.append(s)
 return nl


print(distinguish(f, l2))

# Three 匿名函数

l3 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']


def distinguish(func, array):
 nl = []
 for s in array:
  if func(s):
   nl.append(s)
 return nl

print(distinguish(lambda s: s.rfind('text') + 1, l3))

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

 类似资料:
  • Python 解释器自带的函数叫做内置函数,这些函数可以直接使用,不需要导入某个模块。 如果你熟悉 Shell 编程,了解什么是 Shell 内置命令,那么你也很容易理解什么是 Python 内置函数,它们的概念是类似的。 将使用频繁的代码段封装起来,并给它起一个名字,以后使用的时候只要知道名字就可以,这就是函数。函数就是一段封装好的、可以重复使用的代码,它使得我们的程序更加模块化,不需要编写大量

  • 内置函数 abs() divmod() input() open() staticmethod() all() enumerate() int() ord() str() any() eval() isinstance() pow() sum() basestring() execfile() issubclass() print() super() bin() file() iter() pro

  • 问题内容: Windows XP,Python 2.5: Google App Engine(http://shell.appspot.com/): 这是为什么?我如何拥有一个散列函数,以便在不同平台(Windows,Linux,Mac)上给我相同的结果? 问题答案: 使用hashlib作为 被设计用于: 在字典查找期间快速比较字典键 因此,不保证在所有Python实现中都一样。

  • Python 解释器内置了很多函数,不用 import 即可使用这些内置函数。本小节讲解了 Python 中常见的内置函数,我们将这些函数分为 7 大类: 类别 功能 系统帮助 获取函数的使用帮助 文件 IO 读取标准输入、写标准输出、打开文件 类型转换 将整数转换为字符串、将字符串转换为整数 数学运算 常见的数学运算函数,例如:max 和 min 复合数据类型 列表、元组、字典等数据类型的构造

  • 一、聚合函数: SQLite中支持的聚合函数在很多其他的关系型数据库中也同样支持,因此我们这里将只是给出每个聚集函数的简要说明,而不在给出更多的示例了。这里还需要进一步说明的是,对于所有聚合函数而言,distinct关键字可以作为函数参数字段的前置属性,以便在进行计算时忽略到所有重复的字段值,如count(distinct x)。 函数 说明 avg(x) 该函数返回在同一组内参数字段的平均值。对

  • 本文主要介绍PHP-X内置函数的使用,在PHP扩展开发中,会经常用到这些内置函数,PHP-X的封装,使得调用这些函数像PHP代码一样简单。