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判断for循环最后一次的6种方法

《Python判断for循环最后一次的6种方法》在Python中,通常我们不会直接判断for循环是否正在执行最后一次迭代,因为Python的for循环是基于可迭代对象的,它不知道也不关心迭代的内部状态... 目录1.使用enuhttp://www.chinasem.cnmerate()和len()来判断for

使用Python实现高效的端口扫描器

《使用Python实现高效的端口扫描器》在网络安全领域,端口扫描是一项基本而重要的技能,通过端口扫描,可以发现目标主机上开放的服务和端口,这对于安全评估、渗透测试等有着不可忽视的作用,本文将介绍如何使... 目录1. 端口扫描的基本原理2. 使用python实现端口扫描2.1 安装必要的库2.2 编写端口扫

使用Python实现操作mongodb详解

《使用Python实现操作mongodb详解》这篇文章主要为大家详细介绍了使用Python实现操作mongodb的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、示例二、常用指令三、遇到的问题一、示例from pymongo import MongoClientf

使用Python合并 Excel单元格指定行列或单元格范围

《使用Python合并Excel单元格指定行列或单元格范围》合并Excel单元格是Excel数据处理和表格设计中的一项常用操作,本文将介绍如何通过Python合并Excel中的指定行列或单... 目录python Excel库安装Python合并Excel 中的指定行Python合并Excel 中的指定列P

一文详解Python中数据清洗与处理的常用方法

《一文详解Python中数据清洗与处理的常用方法》在数据处理与分析过程中,缺失值、重复值、异常值等问题是常见的挑战,本文总结了多种数据清洗与处理方法,文中的示例代码简洁易懂,有需要的小伙伴可以参考下... 目录缺失值处理重复值处理异常值处理数据类型转换文本清洗数据分组统计数据分箱数据标准化在数据处理与分析过

Java中Object类的常用方法小结

《Java中Object类的常用方法小结》JavaObject类是所有类的父类,位于java.lang包中,本文为大家整理了一些Object类的常用方法,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. public boolean equals(Object obj)2. public int ha

Python调用另一个py文件并传递参数常见的方法及其应用场景

《Python调用另一个py文件并传递参数常见的方法及其应用场景》:本文主要介绍在Python中调用另一个py文件并传递参数的几种常见方法,包括使用import语句、exec函数、subproce... 目录前言1. 使用import语句1.1 基本用法1.2 导入特定函数1.3 处理文件路径2. 使用ex

Python脚本实现自动删除C盘临时文件夹

《Python脚本实现自动删除C盘临时文件夹》在日常使用电脑的过程中,临时文件夹往往会积累大量的无用数据,占用宝贵的磁盘空间,下面我们就来看看Python如何通过脚本实现自动删除C盘临时文件夹吧... 目录一、准备工作二、python脚本编写三、脚本解析四、运行脚本五、案例演示六、注意事项七、总结在日常使用

Python将大量遥感数据的值缩放指定倍数的方法(推荐)

《Python将大量遥感数据的值缩放指定倍数的方法(推荐)》本文介绍基于Python中的gdal模块,批量读取大量多波段遥感影像文件,分别对各波段数据加以数值处理,并将所得处理后数据保存为新的遥感影像... 本文介绍基于python中的gdal模块,批量读取大量多波段遥感影像文件,分别对各波段数据加以数值处

python管理工具之conda安装部署及使用详解

《python管理工具之conda安装部署及使用详解》这篇文章详细介绍了如何安装和使用conda来管理Python环境,它涵盖了从安装部署、镜像源配置到具体的conda使用方法,包括创建、激活、安装包... 目录pytpshheraerUhon管理工具:conda部署+使用一、安装部署1、 下载2、 安装3