python 内置函数详解(2)

简介: python 内置函数详解(2)

4.16 pop()函数用于移除列表中的一个元素(默认最后一个元素)并且返回该元素的值

#!/usr/bin/python3
#coding=utf-8
list1 = ['Google', 'Runoob', 'Taobao']
list_pop=list1.pop(1)
print "删除的项为 :", list_pop
print "列表现在为 : ", list1
以上实例输出结果如下:
删除的项为 : Runoob
列表现在为 :  ['Google', 'Taobao']

4.17 pow()获取乘方数

$ cat pow1.py
#!/usr/bin/python
import math
print pow(2,3)
print math.pow(2,3)
print 2**3
print 2*3
print pow(2,3,1)
$ python pow1.py
8
8.0
8
6
0

pow(x,y,z) 当 z 这个参数不存在时 x,y 不限制是否为 float 类型, 而当使用第三个参数的时候要保证前两个参数只能为整数。

4.18 seek()用于移动文件读取指针到文件指定的位置

file. seek(offset[, whence])
  • whence:0,1,2三个参数,0表示文件开头,1表示当前位置,2表示文件结尾
  • offset:偏移量,可正可负,正数表示向后移动offset位,负数表示向前移动offset位。
cat log.txt
122222222222222222
1324222222222
24242424242
gsgssgsgssxxnxnxn
sgsgsgsgs
#!/usr/bin/python
#path = 'E:\log.txt'
f = open('E:\log.txt','rb')
print(f.tell())
print(f.read(1))
print(f.tell())
f.seek(5)
print(f.tell())
print(f.read(1))
f.seek(2,1)
print(f.tell())
#print(f.read(1))
f.seek(-1,1)
print(f.tell())
print(f.read(1))
输出:
0
b'1'
1
5
b'6'
8
7
b'8'

4.19 set集合创建

set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

set 语法:

class set([iterable])

参数说明:

iterable – 可迭代对象对象;

集合的相关操作

4.19.1 创建集合

由于集合没有自己的语法格式,只能通过集合的工厂方法set()和frozenset创建

#字典与列表的set

s=set('alex li')
s1= ['alvin', 'ee', 'alvin']
s2=set(s1)
print(s2,type(s2))
print(s,type(s))
output:
{'alvin', 'ee'} <class 'set'>
{'e', 'a', 'x', 'l', 'i', ' '} <class 'set'>

#列表中的列表不可哈希

$ cat set1.py
#!/usr/bin/python
s=[[23,2], 'sgs',34]
s2=set(s)
print(s2)
[root@localhost func]# python set1.py
Traceback (most recent call last):
  File "set1.py", line 3, in <module>
    s2=set(s)
TypeError: unhashable type: 'list'

交集并集差集

>>>x = set('runoob')
>>> y = set('google')
>>> x, y
(set(['b', 'r', 'u', 'o', 'n']), set(['e', 'o', 'g', 'l']))   # 重复的被删除
>>> x & y         # 交集
set(['o'])
>>> x | y         # 并集
set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
>>> x - y         # 差集
set(['r', 'b', 'u', 'n'])
>>>

4.19.2 访问集合

由于集合本身是无序的,所以不能为集合创建索引或切片操作,只能循环遍历或使用in、not in 来 访问或者判断集合元素

s=['alex', 2,3]
s2=set(s)
print(s2)
print(2 in s)
print(4 in s)
print('a' in s)
s2.update('12','zc')
print(s2)
s2.update([12],['wda'])
print(s2)
output;
{3, 2, 'alex'}
True
False
False
{2, 3, '2', 'c', 'alex', 'z', '1'}
{2, 3,  '2', 'c', 'alex', 'z', '1', 12, 'wda'}
output:
s=[‘alex’, 2,3]
s2=set(s)
print(s2)
s2.remove(‘alex’)
print(s2)
output:
{3, 2, ‘alex’}
{3, 2}

4.集合类型操作符

print(set(‘alex’)==set(‘alexxxxxx’))
print(set(‘alex’)<set(‘alexxxxxxw’))
print(set(‘alex’)and set(‘alexxxxxxw’))
print(set(‘alex’) or set(‘alexxxxxxw’))
output:
True
True
{‘w’, ‘e’, ‘x’, ‘a’, ‘l’}
{‘e’, ‘l’, ‘x’, ‘a’}

4.19.3 交集与并集、差集、对称差集(反向交集)、父集

#intersection()
a = set([ 1,2,3,4,5 ])
b = set([4,5,6,7,8])
print(a.intersection(b))
print(a.union(b))
print(a.difference(b))
print(b.difference(a))
print(a.symmetric_difference(b))
print(a.issubset(b))
print(a & b)
print(a | b)
print(a - b)
print(b - a)
print(a ^ b)
output;
{4, 5}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3}
{8, 6, 7}
{1, 2, 3, 6, 7, 8}
False

4.20 strip()它返回的是字符串的副本并删除前导和后缀字符

无参数

a=" \rzha ng\n\t "
print(len(a))
b=a.strip()
print(b)
print(len(b))
输出:
11
zha ng
6

有参数

a="rrbbrrddrr"
b=a.strip("r")
print(b)
输出:bbrrdd

4.21 lstrip()与rstrip分别删除前缀与后缀

$ cat strip1.py
#!/usr/bin/python
a=" zhangkang "
print(a.lstrip(),len(a.lstrip()))
print(a.rstrip(),len(a.rstrip()))
[root@localhost func]# python lstrip.py
('zhangkang ', 10)
(' zhangkang', 10)

4.22 truncate() 方法用于截断文件

如果指定了可选参数 size,则表示截断文件为 size 个字符。 如果没有指定 size,则从当前位置起截断;截断之后 size 后面的所有字符被删除。

truncate() 方法语法如下:

fileObject.truncate( [ size ])

文件 runoob.txt 的内容如下:

1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com

循环读取文件的内容:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开文件
fo = open("runoob.txt", "r+")
print "文件名为: ", fo.name
line = fo.readline()
print "读取第一行: %s" % (line)
# 截断剩下的字符串
fo.truncate()
# 尝试再次读取数据
line = fo.readline()
print "读取数据: %s" % (line)
# 关闭文件
fo.close()
以上实例输出结果为:
文件名为:  runoob.txt
读取第一行: 1:www.runoob.com
读取数据:

以下实例截取 runoob.txt 文件的10个字节:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开文件
fo = open("runoob.txt", "r+")
print "文件名为: ", fo.name
# 截取10个字节
fo.truncate(10)
str = fo.read()
print "读取数据: %s" % (str)
# 关闭文件
fo.close()
以上实例输出结果为:
文件名为:  runoob.txt
读取数据: 1:www.runo

4.23 startswith()与endswith()

startswith判断文本是否以某个或某几个字符开始;

endswith判断文本是否以某个或某几个字符结束;


str.endswith(suffix[, start[, end]])

suffix – 该参数可以是一个字符串或者是一个元素。

start – 字符串中的开始位置。

end – 字符中结束位置。

text = 'Happy National Day!'   
print text.startswith('A')      # False
print text.startswith('H')      # True
print text.startswith('Hap')    # True
print text.startswith('')       # True
print text.endswith('A')        # False
print text.endswith('!')        # True
print text.endswith('Day!')     # True

startswith()和endswith()函数的参数可以包在一个括号中一次列出多个,各个参数之间是或的关系:

text = 'Happy National Day!'      
print text.startswith(('A','H'))   # True
print text.endswith(('y','!'))     # True

endswith典型的应用场景是用来判断是否是某一文件类型(图片或.exe、.sh执行文件)

import os 
import cv2
for item in os.listdir('/home/xxx/TestImage/'):
    if item.endswith(('.jpg','.png','gif')):
        img = cv2.imread(item)
        print True
#!/usr/bin/python
str = "this is string example....wow!!!";
suffix = "wow!!!";
print str.endswith(suffix);
print str.endswith(suffix,20);
suffix = "is";
print str.endswith(suffix, 2, 4);
print str.endswith(suffix, 2, 6);
[root@localhost func]# python startwith.py
True
True
True
False

4.24 tuple() 函数将列表转换为元组。

$ cat tuple.py
#!/usr/bin/python
print tuple([1,2,3,4])
print tuple({1:2,3:4})
print tuple((1,2,3,4))  
aList = [123, 'xyz', 'zara', 'abc'];
aTuple = tuple(aList) 
print "Tuple elements : ", aTuple
[root@localhost func]# python tuple.py
(1, 2, 3, 4)
(1, 3)
(1, 2, 3, 4)
Tuple elements :  (123, 'xyz', 'zara', 'abc')

4.25 with()

一般读写文件

#!/usr/bin/env python
fileReader = open('students.txt', 'r')
for row in fileReader:
    print(row.strip())
fileReader.close()

基本也实现了读取文件的功能。但是有的时候,上述代码在运行的时候会抛出异常,导致无法关闭文件句柄,这个时候,我就会加上异常处理程序,代码就改成了这样:

#!/usr/bin/env python
try:
    fileReader = open('students.txt', 'r')
    for row in fileReader:
        print(row.strip())
except:
    print('Read file failed')
finally:
    fileReader.close()

也还好,解决了抛出一大堆异常的问题。但是上述代码怎么看都有点累赘啰嗦的感觉。那怎么办?

从Python 2.5开始引入了with语句,一种与异常处理相关的功能。


with语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等。比如上面的代码,通过使用with语句改造,就变成了下面这个样子:

#!/usr/bin/env python
with open('students.txt', 'r') as fileReader:
    for row in fileReader:
        print(row.strip())

5. 函数混合

5.1 list 、filter、lambda

$cat test1.py
#!/usr/bin/python
x = range(-5, 5)
new_list = []
for num in x:
   if num < 0:
      new_list.append(num)
print new_list
all_less_than_zero = list(filter(lambda num: num< 0, x))
print all_less_than_zero
[root@localhost func]# python test1.py
[-5, -4, -3, -2, -1]
[-5, -4, -3, -2, -1]

5.2 reduce、lambda

$ cat test2.py
#!/usr/bin/python
product = 1
x = [1, 2, 3, 4]
for num in x:
   product = product * num
print product
product = reduce((lambda x, y: x * y),[1, 2, 3, 4])
print product
[root@localhost func]# python test2.py
24
24

5.3 lambda、map、list

cat test3.py
#!/usr/bin/python
square = lambda x: x * x
print square(3)
x = [1, 2, 3, 4]
def square(num):
   return num * num
print list(map(square, x))
print(list(map(lambda num: num * num,x)))
[root@localhost func]# python test3.py
9
[1, 4, 9, 16]
[1, 4, 9, 16]

参考:

相关文章
|
1天前
|
Python
在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存
在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存在,该函数对路径进行检查,存在则返回True,不存在则返回False。示例代码展示了如何检查&#39;example.txt&#39;文件是否存在并相应打印消息。此外,`os.path.isfile()`用于确认路径是否为文件,仅当是文件时返回True,否则返回False,同样配以示例说明其用法。
8 2
|
2天前
|
Python
【Python操作基础】——函数
【Python操作基础】——函数
|
2天前
|
Python
Python的全局变量作用于整个程序,生命周期与程序相同,而局部变量仅限函数内部使用,随函数执行结束而销毁。
Python的全局变量作用于整个程序,生命周期与程序相同,而局部变量仅限函数内部使用,随函数执行结束而销毁。在函数内部修改全局变量需用`global`关键字声明,否则会创建新局部变量。
9 2
|
5天前
|
Java C# 开发者
Python 中的类型注解是一种用于描述变量、函数参数和返回值预期类型的机制
Python的类型注解提升代码可读性和可维护性,虽非强制,但利于静态类型检查(如Mypy)。包括:变量注解、函数参数和返回值注解,使用内置或`typing`模块的复杂类型,自定义类型注解,以及泛型模拟。类型注解可在变量声明、函数定义和注释中使用,帮助避免类型错误,提高开发效率。
16 6
|
6天前
|
存储 Python
【Python 基础】解释reduce函数的工作原理
【5月更文挑战第6天】【Python 基础】解释reduce函数的工作原理
|
6天前
|
Python
【Python 基础】解释map函数的工作原理
【5月更文挑战第6天】【Python 基础】解释map函数的工作原理
|
6天前
|
索引 Python
【Python 基础】解释Range函数
【5月更文挑战第6天】【Python 基础】解释Range函数
|
7天前
|
Python
Python中的匿名函数,即lambda函数
【5月更文挑战第6天】Python中的匿名函数,即lambda函数,用于简洁地定义小型函数,无需`def`关键字。示例:`double = lambda x: x * 2`,可将5加倍。常用于排序(自定义比较)、映射(如求平方)和过滤列表,以及作回调函数。然而,它们不适用于多行代码或复杂逻辑,此时需用常规函数。
4 0
|
11天前
|
NoSQL Serverless Python
在Python的Pandas中,可以通过直接赋值或使用apply函数在DataFrame添加新列。
在Python的Pandas中,可以通过直接赋值或使用apply函数在DataFrame添加新列。方法一是直接赋值,如`df[&#39;C&#39;] = 0`,创建新列C并初始化为0。方法二是应用函数,例如定义`add_column`函数计算A列和B列之和,然后使用`df.apply(add_column, axis=1)`,使C列存储每行A、B列的和。
38 0
|
13天前
|
机器学习/深度学习 数据可视化 TensorFlow
Python用线性回归和TensorFlow非线性概率神经网络不同激活函数分析可视化
Python用线性回归和TensorFlow非线性概率神经网络不同激活函数分析可视化