算上Python Lambda函数

时间:2015-10-13 22:31:32

标签: python lambda reduce

我正在学习Python中的Lambda并且为了学习,想要在Lambda中实现所有内容 - 我读了很多帖子,写出神秘的lambda代码并不是一个好主意。然而,这个练习只是为了学习。

给定一个数字和字符列表,计算数字和字符数

使用lambda

实现以下内容
mylist = ['abc', '123', '758', 'cde']

d =0
c =0
for l in mylist:
        if l.isdigit():
                d+=1;
        if l.isalpha():
                c+=1

print d, c

如果你能解释一下这个解决方案,它会很棒!

到目前为止我尝试过,我只能得到一个变量

mylist = "abc 123 758 cde"
print reduce(lambda x, y: x+y, map(lambda x: x.isdigit(),mylist.split(' ')))

3 个答案:

答案 0 :(得分:2)

你可以把它作为一个lambda来实现,但我真的希望你不会。它像罪一样丑陋,一半有用。

f = lambda lst: (sum(1 for el in lst if el.isdigit()),
                 sum(1 for el in lst if el.isalpha()))

mylst = ['abc', '123', '758', 'cde']

f(mylst)  # (2, 2)

答案 1 :(得分:2)

apart from lambda there are other thrilling functional capabilities in python

# map isalpha on mylist, count True
ct = list(map(str.isalpha, mylist)).count(True)

print(ct)

2

# map isdigit on mylist, count True
ct = list(map(str.isdigit, mylist)).count(True)

print(ct)

2

答案 2 :(得分:1)

d,c = reduce(lambda (x,y),(a,b): (x+a, y+b),
        [(e.isdigit(),e.isalpha()) for e in mylist],
        (0,0))

它看起来足够神秘吗?你想保留这样的代码吗?

Python3中的情况更糟糕

d, c = reduce(lambda x_y, a_b: (x_y[0]+a_b[0], x_y[1]+a_b[1]),
              [(e.isdigit(), e.isalpha()) for e in mylist],
              (0, 0))