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中各种常见文件(txt,xls,csv,sql,二进制文件)的读写操作与类型转换,感兴趣的小伙伴可以跟... 目录1.文件txt读写标准用法1.1写入文件1.2读取文件2. 二进制文件读取3. 大文件读取3.1

使用Python实现一个优雅的异步定时器

《使用Python实现一个优雅的异步定时器》在Python中实现定时器功能是一个常见需求,尤其是在需要周期性执行任务的场景下,本文给大家介绍了基于asyncio和threading模块,可扩展的异步定... 目录需求背景代码1. 单例事件循环的实现2. 事件循环的运行与关闭3. 定时器核心逻辑4. 启动与停

基于Python实现读取嵌套压缩包下文件的方法

《基于Python实现读取嵌套压缩包下文件的方法》工作中遇到的问题,需要用Python实现嵌套压缩包下文件读取,本文给大家介绍了详细的解决方法,并有相关的代码示例供大家参考,需要的朋友可以参考下... 目录思路完整代码代码优化思路打开外层zip压缩包并遍历文件:使用with zipfile.ZipFil

Python处理函数调用超时的四种方法

《Python处理函数调用超时的四种方法》在实际开发过程中,我们可能会遇到一些场景,需要对函数的执行时间进行限制,例如,当一个函数执行时间过长时,可能会导致程序卡顿、资源占用过高,因此,在某些情况下,... 目录前言func-timeout1. 安装 func-timeout2. 基本用法自定义进程subp

Python实现word文档内容智能提取以及合成

《Python实现word文档内容智能提取以及合成》这篇文章主要为大家详细介绍了如何使用Python实现从10个左右的docx文档中抽取内容,再调整语言风格后生成新的文档,感兴趣的小伙伴可以了解一下... 目录核心思路技术路径实现步骤阶段一:准备工作阶段二:内容提取 (python 脚本)阶段三:语言风格调

Python结合PyWebView库打造跨平台桌面应用

《Python结合PyWebView库打造跨平台桌面应用》随着Web技术的发展,将HTML/CSS/JavaScript与Python结合构建桌面应用成为可能,本文将系统讲解如何使用PyWebView... 目录一、技术原理与优势分析1.1 架构原理1.2 核心优势二、开发环境搭建2.1 安装依赖2.2 验

一文详解如何在Python中从字符串中提取部分内容

《一文详解如何在Python中从字符串中提取部分内容》:本文主要介绍如何在Python中从字符串中提取部分内容的相关资料,包括使用正则表达式、Pyparsing库、AST(抽象语法树)、字符串操作... 目录前言解决方案方法一:使用正则表达式方法二:使用 Pyparsing方法三:使用 AST方法四:使用字

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

Python运行中频繁出现Restart提示的解决办法

《Python运行中频繁出现Restart提示的解决办法》在编程的世界里,遇到各种奇怪的问题是家常便饭,但是,当你的Python程序在运行过程中频繁出现“Restart”提示时,这可能不仅仅是令人头疼... 目录问题描述代码示例无限循环递归调用内存泄漏解决方案1. 检查代码逻辑无限循环递归调用内存泄漏2.

Python中判断对象是否为空的方法

《Python中判断对象是否为空的方法》在Python开发中,判断对象是否为“空”是高频操作,但看似简单的需求却暗藏玄机,从None到空容器,从零值到自定义对象的“假值”状态,不同场景下的“空”需要精... 目录一、python中的“空”值体系二、精准判定方法对比三、常见误区解析四、进阶处理技巧五、性能优化