Python3学习笔记之库函数

本文记录Python3中的一些常用的库函数

  • input:input函数用于输入,它返回的值是str类型。在input中加上字符串可以作为提示语句来显示在屏幕上:
>>> name = input('please enter your name: ')
please enter your name: chenf99
>>> print('hello,', name)
hello, chenf99
  • range:range函数可用于产生一个整数序列,再通过list函数可以转换为list:
>>> list(range(5))
[0, 1, 2, 3, 4]
  • 各种用于转换类型的函数:int()float()str()bool()hex()
>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> str(100)
'100'
>>> bool(1)
True
>>> bool('')
False
>>> hex(1024)
'0x400'
  • findrfind函数检测在字符串的指定范围内是否包含某个子串,如果包含则返回子串开始的索引值,不包含则返回-1。它们的区别是find为从左向右找,rfind为从右向左找
str.find(str, beg=0, end=len(string))
str.rfind(str, beg=0 end=len(string))
  • strip()、lstrip()、rstrip()分别除去两端、左端、右端指定的字符,默认为去除空白字符
str = "123abcrunoob321"
print (str.strip( '12' ))

3abcrunoob3
  • split函数通过指定的分隔符对字符串进行切片,并且可以指定分割次数,分割结果是字符串列表。仅支持单一分隔符,且不感知空格数量
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );
print str.split(' ', 1 );

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
  • 列表相关函数:append、extend、insert、remove、reverse
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

a = [1, 2, 3]
b = [5, 6]
a.append(b)         #添加一个元素
print(a)            #[1, 2, 3, [5, 6]]
a.extend(b)         #添加其他列表中的元素
print(a)            #[1, 2, 3, [5, 6], 5, 6]
a.insert(1, 'K')
print(a)            #[1, 'K', 2, 3, [5, 6], 5, 6]
a.insert(3, 'K')
print(a)            #[1, 'K', 2, 'K', 3, [5, 6], 5, 6]
a.remove(a[3])      #删除第一个a[3]元素
print(a)            #[1, 2, 'K', 3, [5, 6], 5, 6]
a.insert(1, 'K')    #1, 'K', 2, 'K', 3, [5, 6], 5, 6]
del a[3]            #删除a中指定位置(3)上的元素
print(a)            #1, 'K', 2, 3, [5, 6], 5, 6]
a.reverse()
print(a)            #[6, 5, [5, 6], 3, 2, 'K', 1]
print(a.index('K')) #5
  • map函数根据提供的函数来对指定的序列进行映射,python2.x中返回值是列表,python3.x中返回值是迭代器
map(function, iterable, ...)

#function--判断函数
#iterable--可迭代对象
>>> def square(x):
...     return x ** 2
...
>>> list(map(square, [1, 2, 3]))
[1, 4, 9]
>>> tuple(map(square, [1, 2, 3]))
(1, 4, 9)

#也可使用lambda匿名函数
>>> list(map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6]))
[5, 7, 9]
  • filter函数根据提供的函数过滤掉指定序列中的一些元素,python2.7中返回列表,python3.x中返回迭代器
filter(function, iterable)  #只有两个参数

#function--判断函数
#iterable--可迭代对象
>>> def is_odd(x):
...     return x % 2 != 0
... 
>>> list(filter(is_odd, range(1, 10)))
[1, 3, 5, 7, 9]
#同样可以使用lambda表达式
>>> list(filter(lambda x: x % 2 != 0, range(1, 10)))
[1, 3, 5, 7, 9]
  • reduce函数主要对列表中的元素进行累积,累积的方法是提供的函数,返回值是计算结果
reduce(function, iterable[, initializer])

function -- 函数,有两个参数
iterable -- 可迭代对象
initializer -- 可选,初始参数
使用方法:
from functools import reduce

print(reduce(lambda x, y: x ** y, [2, 3, 4]))   
#2^3^4 = 8^4 = 4096
实现:
def myReduce(function,sequence,startValue):
    for x in sequence:
        startValue = function(startValue,x)
    return startValue

猜你喜欢

转载自blog.csdn.net/chenf1999/article/details/81227451