Python中一些常用函数总结

一.字符串的便捷操作以及注意事项:

1.'字符串'.split('分隔符')       #用于分割字符串

Example:

In [5]: s ='updata::sername::acct'

In [6]: s.split("::")
Out[6]: ['updata', 'sername', 'acct']

2.'字符串'.join('interable')     #用于分割字符串

注意:join后的可迭代对象里面的元素必须为字符串

Example:

In [8]: l = ['ada','da','dad',43]

In [9]: ','.join(l)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-ba2bb76dcfa6> in <module>()
----> 1 ','.join(l)

TypeError: sequence item 3: expected str instance, int found

此时若列表l中有整型,则会报错,用法如下。

Example:

In [10]: l = ['ada','da','dad','43']

In [11]: ','.join(l)
Out[11]: 'ada,da,dad,43'

3.find  #用于找字符串中特定的字符串 

没有找到的话返回-1

找到的话返回第一个字母的索引

Example:

In [43]: a ='sasafaewflove'

In [44]: a.find('love')
Out[44]: 9

4.lower,upper    #返回字符串的小写大写,比较简单  不再举例

5.strip  #去掉字符串两边的空格

6.replace,translate    #替换字符串中特定的位置

replace可以替换多个字符

Example:

In [46]: "this is a test".replace("is",'eez')
Out[46]: 'theez eez a test'

7.translate    只能替换单个字符,并且可以同时替换多个字符,因此效率比replace要高。

使用前必须创建一个转换表:

Example:

In [47]: table = str.maketrans('cs','kz')

In [48]: table
Out[48]: {99: 107, 115: 122}

In [49]: 'this is an incredible test'.translate(table)
Out[49]: 'thiz iz an inkredible tezt'

8.判断字符串是否满足一定的特定条件

isalum                          方法检测字符串是否由字母和数字组成。

isalpha                        方法检测字符串是否只由字母组成。

isdecimal                     方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。

isdigit                           方法检测字符串是否只由数字组成。

isdentifier                     是否是python中的标识符

islower                         方法检测字符串是否由小写字母组成。

isnumeric                     方法检测字符串是否只由数字组成。这种方法是只针对unicode对象。

isprintable                    判断字符串中所有字符是否都是可打印字符(in repr())或字符串为空。

isspace                        方法检测字符串是否只由空格组成。

istitle                            方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。

isupper                         方法检测字符串中所有的字母是否都为大写。

 

9.sorted   #用于可迭代对象自定义排序(放在最后,因为不是字符串自带的方法,但是很有用)

注意:sorted函数不同于列表中的sort方法。列表的sort方法没有返回值,直接对列表本身进行操作,而sorted函数返回可迭代对象

Example:给字典按键值的升序排序
 

a = {1:a,2:b,3:c}

In [40]: sorted(a.items(),key = lambda x:x[0])
Out[40]: [(1, 'a'), (2, 'b'), (3, 'c')]

 

小技巧:如果我们队一些整数数字排序输出,并且要求输出形式要为:1,2,3,4

要求除了最后一个数字其余每一个数字后面都有逗号

这种情况下,遍历数组并且做判断是比较麻烦的,可以使用join函数解决这个问题。

Example:字典的升序输出,要求输出格式如上:

In [17]: a= {1:"a",3:"c",2:"b"}

In [18]: print(",".join([str(x) for x in sorted(list(a.keys()))]))

因为sorted默认排序就是字典的键值所以可以简单写为:

In [38]: print(','.join([str(x) for x in sorted(a)]))
1,2,3

 

二.map,reduce,filter函数

map语法

map(function, iterable, ...)

Example:

>>>def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

reduce函数与map函数有异曲同工之妙:

reduce() 函数语法:

reduce(function, iterable[, initializer])

Example:

>>>def add(x, y) :            # 两数相加
...     return x + y
... 
>>> reduce(add, [1,2,3,4,5])   # 计算列表和:1+2+3+4+5
15
>>> reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函数
15

filter() 方法的语法:

filter(function, iterable)

Example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def is_odd(n):
    return n % 2 == 1
 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)
输出结果 :

[1, 3, 5, 7, 9]

小技巧:我们可以用filter()这个方法简化我们求素数的函数。如下:

 

def IsPrmi(x):
    if x ==2:
        return True
    else:
        for i in range(2,x//2+1):
            if x % i == 0:
                return False
        return True

l= list(x for x in filter(IsPrmi,range(1,101)))
print(l)

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值