python对列表元素执行函数操作
天蓬老师
天蓬老师 2017-04-17 17:02:51
0
2
494
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
洪涛

lambda can only define an expression for calculation. You also need map or list comprehension to call this lambda:

The map function has two parameters. The first parameter is a function (lambda or named function), and the second parameter is an iterable object (list, tuple). map will take one element at a time and pass it to lambda. function, and retrieve the result;map将每次取一个元素传递给lambda函数,并取回结果;

# lambda实现一个没有名字的函数

# lambda 参数名 : 处理参数的表达式
lambda x: x if str(x).isdigit() else str(x).replace('网站', 'xxx网站xxx')

鉴于你既然有多个需要处理的key, 而lambda后面的语句必须是一个可以直接返回具体值的简单表达式, lambda不再适合这种场景, 可以直接构造函数

demolist = [1,'这是一个问答网站','没错,网站里高手如云。']

key = {'网站':'Net','高手':"Master"}
def trans(each):
    global key
    for k in key:
        if type(each) is str and k in each:
            each = each.replace(k, key[k])
    return each

demolist = map(trans, demolist)

for each in demolist:
    print each
λ  ~/  python x.py 
1
这是一个问答Net
没错,Net里Master如云。
Since you have multiple keys that need to be processed, and the statement after lambda must be a simple expression that can directly return a specific value, lambda is no longer suitable for this scenario, you can directly Constructor:

rrreee

If you are familiar with the re module above, you can also use it, but that is another topic. 🎜
Ty80
import re

def insert_b(demo):
    if type(demo) is str:
        demo = re.sub('(网站|高手)', r'<b></b>', demo)
    return demo

demolist2 = map(insert_b, demolist1)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template