python内置函数

map函数

map() 会根据提供的函数对指定序列做映射。map
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

语法

map() 函数语法:
map(function, iterable, ...)

参数

function -- 函数
iterable -- 一个或多个序列

返回值

Python 2.x 返回列表。
Python 3.x 返回迭代器。

*map(func, list)

大家知道,map返回的map 类;要输出需转换(如输出list,需使用list()转换)。
加*之后,map()返回的iterable将被解包为函数的参数。也就是说,不是调用函数并将iterable对象作为单个参数传递,而是将iterable的各个元素作为单个参数传递。
例子:

>>> def foo(a, b, c): print "a:%s b:%s c:%s" % (a, b, c)
...
>>> x = [1,2,3]
>>> foo(*x)
a:1 b:2 c:3

所有*的意思都是这样,将一个元组或列表作为一个参数输入,但处理时却把每个元素单独解压出来传入函数中。

再如下例:

    ##Vocabulary类中某函数定义
    @_check_build_vocab 
    def index_dataset(self, *datasets, field_name, new_field_name=None):
	##函数调用
vocab.index_dataset(train_data, dev_data, test_data, field_name='words')

使用map对['1', '2', '4', '8']转换为整数列表

mp=map(lambda x: int(x), str1.split(','))
print(mp) # map返回的是迭代器,可以转换为list输出
print(list(mp))

<map at 0x2c0ca215518>
[1, 2, 4, 8]

使用def函数map:

>>> def square(x) :            # 计算平方数
>>> ...     return x ** 2
>>> ...
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
>>> [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]

strip函数

Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
title,source=title_long.strip('[').split(']')

str = "123abcrunoob321"
print (str.strip( '12' ))  # 字符序列为 12

output:
3abcrunoob3
'中国政府网', '增值税发票数据显示:“十三五”时期我国产业扶贫、消费扶贫成果丰硕'

split函数

str = "this is string example....wow!!!"
print (str.split( ))       # 以空格为分隔符
print (str.split('i',1))   # 以 i 为分隔符; 从左向右找分割符:分割几次。
print (str.split('w'))     # 以 w 为分隔符

对字符串split

str1="1,2,4,8"
str1.split(',') # out:['1', '2', '4', '8']

insert函数

功能 insert()函数用于将指定对象插入列表的指定位置。
语法 list.insert(index, obj)

index函数

若没有查到,返回-1(而find是抛出异常)。

posted @ 2021-02-27 22:12  zae  阅读(67)  评论(0编辑  收藏  举报