python之常用builtins

2024-04-10 03:38
文章标签 python 常用 builtins

本文主要是介绍python之常用builtins,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

分为class和function

1. class
1.1 class range

help(__builtins__.range)
class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  Return a sequence of numbers from start to stop by step.
平时我们在for循环中经常用到range,其实这里的range是类而非function
python3.x中range取代了xrange,从原来的内置函数变成了类

for num in range(4):print(num, end = ' ')
output:

0 1 2 3 
1.2 class 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.
values = ['1', '2', '-3', '-', '4', 'N/A', '5']
def is_int(val):try:if int(val):return Trueexcept ValueError:return False
ivals = list(filter(is_int, values))
print(ivals)
output:

['1', '2', '-3', '4', '5']

1.3 class enumerate
class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |  
 |  Return an enumerate object.  iterable must be another object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument.
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

S = 'abcdefghijk'
for (index,char) in enumerate(S):print(str(index).center(2), end = ' ')print(char)
output:

0  a
1  b
2  c
3  d
4  e
5  f
6  g
7  h
8  i
9  j
10 k
1.4 class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 |  
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.
1.4.1
一般应用

#列表以及迭代器的压缩和解压缩
ta = [1,2,3]
tb = [9,8,7]
tc = ['a','b','c']
for (a,b,c) in zip(ta,tb,tc):print(a,b,c)# cluster
# zipped is a generator
zipped = zip(ta,tb)
print(zipped)
print(type(zipped))# decompose
na, nb = zip(*zipped)
print(na, nb)
output:

1 9 a
2 8 b
3 7 c
<zip object at 0x00000000023CDEC8>
<class 'zip'>
(1, 2, 3) (9, 8, 7)
1.4.2
列表相邻元素压缩器

zip(*[iter(s)]*n)应用
How does zip(*[iter(s)]*n) work in Python? 
解释1:
iter() is an iterator over a sequence. [x] * n produces a list containing n quantity of x, i.e. a list of length n, 
where each element is x. *arg unpacks a sequence into arguments for a function call. 
Therefore you're passing the same iterator 3 times to zip(), and it pulls an item from the iterator each time.
解释2:
iter(s) returns an iterator for s.
[iter(s)]*n makes a list of n times the same iterator for s.
So, when doing zip(*[iter(s)]*n), it extracts an item from all the three iterators from the list in order. 
Since all the iterators are the same object, it just groups the list in chunks of n.

example1:

s = [1,2,3,4,5,6,7,8,9]
n = 3zz = zip(*[iter(s)]*n) # returns [(1,2,3),(4,5,6),(7,8,9)]
for i in zz:print(i)
output:

(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
example2:

x = iter([1,2,3,4,5,6,7,8,9])
for i in zip(x, x, x):print(i)
output:

(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
1.4.3
针对上面的扩展

One word of advice for using zip like 1.4.2. It will truncate your list if it's length is not evenly divisible.
you could use something like this:
def n_split(iterable, n):num_extra = len(iterable) % nzipped = zip(*[iter(iterable)] * n)return list(zipped) if not num_extra else list(zipped) + n_split(iterable[-num_extra:],num_extra)for ints in n_split(range(1,12), 3):print(', '.join([str(i) for i in ints]))
output:

1, 2, 3
4, 5, 6
7, 8, 9
10, 11
注:
a.帖子上对n_split函数的return是return zipped if not num_extra else zipped + [iterable[-num_extra:], ],
但是这样会报错 TypeError: unsupported operand type(s) for +: 'zip' and 'list',所以最终修改成以上形式。
b.print(', '.join([str(i) for i in ints])) 中i必须是str形式,不然会报错
1.4.4 针对二维矩阵的行列互换
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = map(list,zip(*a))
for i in b:print(i)
output:

[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
1.4.5 反转字典
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(dict(zip(m.values(), m.keys())))
output:

{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
1.5 class map
class map(object)
 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
re = map((lambda x,y: x+y),[1,2,3],[6,7,9])
for i in re:print(i)
output:

7
9
12
1.6 class slice
class slice(object)
 |  slice(stop)
 |  slice(start, stop[, step])
 |  
 |  Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).
 |  
 |  Methods defined here:
 |  indices(...)
 |      S.indices(len) -> (start, stop, stride)
 |      
 |      Assuming a sequence of length len, calculate the start and stop
 |      indices, and the stride length of the extended slice described by
 |      S. Out of bounds indices are clipped in a manner consistent with the
 |      handling of normal slices.
 |  Data descriptors defined here:
 |  start
 |  step
 |  stop
#命名列表切割方式
a = [0, 1, 2, 3, 4, 5]
ind = slice(-3, None)
print(a[ind]) 
for i in ind.indices(6):print(i)  
print(a[3:6:1])
#由上脚本可知indices其实就是对slice的一种解释,其实把slice(-3, None)变成slice(3,6,1)结果也是一样的
output:

[3, 4, 5]
3
6
1
[3, 4, 5]

2. built-in functions:
2.1 built-in function iter 

iter(...)
    iter(iterable) -> iterator
    iter(callable, sentinel) -> iterator
    
    Get an iterator from an object.  In the first form, the argument must
    supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.
for i in iter(range(5)):print(i, end = ' ')
output:

0 1 2 3 4
2.2 built-in function min
min(...)
    min(iterable, *[, default=obj, key=func]) -> value
    min(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its smallest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the smallest argument.
# for the tow methods, we give the examples, as follows:
# Data reduction across fields of a data structure
portfolio = [{'name':'GOOG', 'shares': 50},{'name':'YHOO', 'shares': 75},{'name':'AOL', 'shares': 20},{'name':'SCOX', 'shares': 65}
]
print(min(p['shares'] for p in portfolio))
print(min(portfolio, key = lambda x: x['shares']))
output:

20
{'name': 'AOL', 'shares': 20}
2.3 Help on built-in function eval
eval(...)
    eval(source[, globals[, locals]]) -> value
    
    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.
eval()函数十分强大,官方demo解释为:将字符串str当成有效的表达式来求值并返回计算结果。so,结合math当成一个计算器很好用。
其他用法,可以把list,tuple,dict和string相互转化。见下例子:
>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> print(type(eval(a)))
<class 'list'>
另一个例子:

# Compute area with console input
import math
# Prompt the user to enter a radius
radius = eval(input("Enter a value for radius:"))
# compute area
area = pow(radius, 2) * math.pi
# Display results
print("The area for the circle of radius", radius, "is", area)


这篇关于python之常用builtins的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/889982

相关文章

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Python包管理工具pip的升级指南

《Python包管理工具pip的升级指南》本文全面探讨Python包管理工具pip的升级策略,从基础升级方法到高级技巧,涵盖不同操作系统环境下的最佳实践,我们将深入分析pip的工作原理,介绍多种升级方... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核