Python中这两个函数有什么区别?

时间:2018-01-30 19:09:13

标签: python

有人可以向我解释这两个函数之间的区别以及我得到两个不同值的原因是什么?

1

def longest_consec(starr, k):
    n = len(starr)
    if n == 0 or k > n or k <= 0 :
        return ""  
    for i in range(n-k+1):
        lst = starr[i:i+k]
        return ''.join(lst)

print(longest_consec(["zone", "abigail", "theta", "form", "libe", "zas"], 2))

输出:libezas

2

def longest_consec(strarr, k):
    n = len(strarr)
    if n == 0 or k > n or k <= 0 :
        return ""
    lst = [''.join(strarr[i:i+k]) for i in range(len(strarr)+1-k)]
    return lst

print(longest_consec(["zone", "abigail", "theta", "form", "libe", "zas"], 2))

输出:['zoneabigail', 'abigailtheta', 'thetaform', 'formlibe', 'libezas']

1 个答案:

答案 0 :(得分:0)

def longest_consec(starr, k):
    n = len(starr)
    if n == 0 or k > n or k <= 0 :
        return ""
    for i in range(n-k+1): #this loop is pretty strange, it can be replace by starr[n-k:n] that means create a list with the k last element of starr
        lst = starr[i:i+k]
        #print(lst) -> visualize it
    return ''.join(lst) #concat k last element, ["libe", "zas"] -> "libezas"

def longest_consecbis(strarr, k):
    n = len(strarr)
    if n == 0 or k > n or k <= 0 :
        return ""
    lst = [''.join(strarr[i:i+k]) for i in range(len(strarr)+1-k)] #create an array of string obtained by joining k by k elements (concat)
    #[], k = 2
    #loop 0 -> ["zone, abigail"] -> "zoneabigail" -> add it to the list : result ["zoneabigail"]
    #loop 1 -> ["abigail", "theta"] -> "abigailtheta" -> add it to the list : result ["zoneabigail", "abigailtheta"]
    return lst

将第二个与第一个相匹配,如下所示:

def secondWithOne(starr, k):
    n = len(starr)
    if n == 0 or k > n or k <= 0 :
        return ""
    arr = []
    for i in range(n-k+1):
        arr.append(''.join(starr[i:i+k]))
    return arr