簡體   English   中英

如何在python中將復雜函數轉換為lambda?

[英]How do I convert complex function to lambda in python?

我正在考慮將更復雜的函數轉換為lambda並將其放在地圖而不是f中的方法。 函數是這樣的:

#this function should be in lambda
def f(s):
    if (type(s) == int):
        return s*2
    else:
        return s.replace('r', '*')

lst = [4,5,6,'rer', 'tr',50,60]
lst = list(map( f, lst))
#result of lst is [8, 10, 12, '*e*', 't*', 100, 120]
#lst = list(map ( lambda x.... , lst))

還是lambda只應該處理短函數? 大的必須分解為單獨的功能嗎?

lambda使用if else語句:

print(list(map(lambda x: x*2 if type(x)==int else x.replace('r','*'),lst)))

輸出:

[8, 10, 12, '*e*', 't*', 100, 120]

更好的是,使用isinstance

print(list(map(lambda x: x*2 if isinstance(x,int) else x.replace('r','*'),lst)))

isinstance代替type

lst = [4,5,6,'rer', 'tr',50,60]
lst = list(map(lambda x: x*2 if isinstance(x, int) else x.replace('r', '*'), lst))

lst
[8, 10, 12, '*e*', 't*', 100, 120]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM