简体   繁体   English

For 循环还是 Lambda 函数?

[英]For loop or Lambda function?

I have this two code, they both (only the first right now) should return me the lenght of sequence that is repeated (13, 6, 6, 14, 6 AND 13, 6, 6, 14, 6):我有这两个代码,它们(现在只有第一个)应该返回我重复的序列长度(13, 6, 6, 14, 6 AND 13, 6, 6, 14, 6):

l = [13, 6, 6, 14, 6, 13, 6, 6, 14, 6]

def count_period(l): 
    
    l_max = int((len(l)/2)+1)

    for i in range(2, l_max):
        interval1 = l[0:i] 
        intervallo2 = l[i:2*i]
        if interval1 == interval2:
            return i

And:和:

l = [13, 6, 6, 14, 6, 13, 6, 6, 14, 6]

l_max = int((len(l)/2)+1)
period_value= next(filter(lambda x: [l[0:x] == l[x:2*x] in range(2, l_max)], l), None)

Why the first code return the right value (5) while the second return me 13?为什么第一个代码返回正确的值 (5) 而第二个返回我 13? What I'm doing wrong?我做错了什么? About this topic: since I'm newbie to Python from a general point of view (and not about this case), how I can know which path should i follow to get a good code (with low execution time and low cyclomatic complexity)?关于这个主题:因为从一般的角度来看我是 Python 的新手(而不是关于这种情况),我如何知道我应该遵循哪条路径来获得好的代码(执行时间短,圈复杂度低)? For example in this case (let us assume that I haven't written anything yet), which of this two way (or another) should I follow?例如在这种情况下(让我们假设我还没有写任何东西),我应该遵循这两种方式(或另一种方式)中的哪一种? Thank you!谢谢!

You should be filtering range(2, l_max) not l to translate your code from the top into a filter.您应该过滤range(2, l_max)而不是l以将您的代码从顶部转换为过滤器。 Right now for each value in l you are creating a list in the predicate lamdba you define filter to use.现在,对于l每个值,您正在定义要使用的过滤器的谓词 lamdba 中创建一个列表。 If that list has items in it it returns true , only the empty list would return false .如果该列表中有项目,则返回true ,只有空列表会返回false Filter then decides to keep the value x if it passes the predicate or discards it if it does not.然后,如果过滤器通过谓词,则过滤器决定保留值x ,否则将其丢弃。 So therefore it keeps all items in the original list and next on that list is 13. You should do this instead:因此,它保留原始列表中的所有项目,该列表中的next是 13。您应该这样做:

l = [13, 6, 6, 14, 6, 13, 6, 6, 14, 6]

l_max = int((len(l)/2)+1)
period_value= next(filter(lambda x: l[0:x] == l[x:2*x], range(2, l_max)), None)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM