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

相关文章

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

Python设置Cookie永不超时的详细指南

《Python设置Cookie永不超时的详细指南》Cookie是一种存储在用户浏览器中的小型数据片段,用于记录用户的登录状态、偏好设置等信息,下面小编就来和大家详细讲讲Python如何设置Cookie... 目录一、Cookie的作用与重要性二、Cookie过期的原因三、实现Cookie永不超时的方法(一)

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos