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如何下载网络文件到本地指定文件夹

《python如何下载网络文件到本地指定文件夹》这篇文章主要为大家详细介绍了python如何实现下载网络文件到本地指定文件夹,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下...  在python中下载文件到本地指定文件夹可以通过以下步骤实现,使用requests库处理HTTP请求,并结合o

Python实现获取带合并单元格的表格数据

《Python实现获取带合并单元格的表格数据》由于在日常运维中经常出现一些合并单元格的表格,如果要获取数据比较麻烦,所以本文我们就来聊聊如何使用Python实现获取带合并单元格的表格数据吧... 由于在日常运维中经常出现一些合并单元格的表格,如果要获取数据比较麻烦,现将将封装成类,并通过调用list_exc

Python logging模块使用示例详解

《Pythonlogging模块使用示例详解》Python的logging模块是一个灵活且强大的日志记录工具,广泛应用于应用程序的调试、运行监控和问题排查,下面给大家介绍Pythonlogging模... 目录一、为什么使用 logging 模块?二、核心组件三、日志级别四、基本使用步骤五、快速配置(bas

Python日期和时间完全指南与实战

《Python日期和时间完全指南与实战》在软件开发领域,‌日期时间处理‌是贯穿系统设计全生命周期的重要基础能力,本文将深入解析Python日期时间的‌七大核心模块‌,通过‌企业级代码案例‌揭示最佳实践... 目录一、背景与核心价值二、核心模块详解与实战2.1 datetime模块四剑客2.2 时区处理黄金法

Spring Boot 常用注解整理(最全收藏版)

《SpringBoot常用注解整理(最全收藏版)》本文系统整理了常用的Spring/SpringBoot注解,按照功能分类进行介绍,每个注解都会涵盖其含义、提供来源、应用场景以及代码示例,帮助开发... 目录Spring & Spring Boot 常用注解整理一、Spring Boot 核心注解二、Spr

Python文件操作与IO流的使用方式

《Python文件操作与IO流的使用方式》:本文主要介绍Python文件操作与IO流的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python文件操作基础1. 打开文件2. 关闭文件二、文件读写操作1.www.chinasem.cn 读取文件2. 写

使用Python自动化生成PPT并结合LLM生成内容的代码解析

《使用Python自动化生成PPT并结合LLM生成内容的代码解析》PowerPoint是常用的文档工具,但手动设计和排版耗时耗力,本文将展示如何通过Python自动化提取PPT样式并生成新PPT,同时... 目录核心代码解析1. 提取 PPT 样式到 jsON关键步骤:代码片段:2. 应用 JSON 样式到

python通过curl实现访问deepseek的API

《python通过curl实现访问deepseek的API》这篇文章主要为大家详细介绍了python如何通过curl实现访问deepseek的API,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编... API申请和充值下面是deepeek的API网站https://platform.deepsee

Python Selenium动态渲染页面和抓取的使用指南

《PythonSelenium动态渲染页面和抓取的使用指南》在Web数据采集领域,动态渲染页面已成为现代网站的主流形式,本文将从技术原理,环境配置,核心功能系统讲解Selenium在Python动态... 目录一、Selenium技术架构解析二、环境搭建与基础配置1. 组件安装2. 驱动配置3. 基础操作模

Java中的内部类和常用类用法解读

《Java中的内部类和常用类用法解读》:本文主要介绍Java中的内部类和常用类用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录内部类和常用类内部类成员内部类静态内部类局部内部类匿名内部类常用类Object类包装类String类StringBuffer和Stri