Home  >  Q&A  >  body text

python对列表元素执行函数操作

天蓬老师天蓬老师2766 days ago489

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 17:04:51

    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. 🎜

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:04:51

    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)

    reply
    0
  • Cancelreply