比较两个列表和“回顾”

时间:2011-07-20 04:53:26

标签: python

你如何比较两个名单和“回顾”?

我正在比较两个列表的元素:

score = 0
for (x,y) in zip(seqA,seqB):

    if x == y:
        score = score +1

    if x !=y :
        score = score - 1

现在我希望score + 3如果之前的对匹配,那么基本上我必须“回顾”一次迭代。

4 个答案:

答案 0 :(得分:3)

只需保存上一场比赛的结果。

score = 0
prev  = 0

for (x,y) in zip(seqA,seqB):

    if x == y:
        if prev == 1:
            score = score +3
        else:
            score = score +1
        prev = 1

    if x !=y :
        score = score - 1
        prev = 0

答案 1 :(得分:0)

可能有更直接的方式,但明确也不错。
添加的想法引入了一个变量,该变量告诉我们下次匹配时要添加的金额。

score = 0
matchPts = 1                   // by default, we add 1
for (x,y) in zip(seqA,seqB):

    if x == y:
        score = score + matchPts 
        matchPts = 3 

    if x !=y :
        score = score - 1
        matchPts = 1

可以引入多个连续比赛的更复杂的奖励等级,并进行一些更改:

score = 0
consecutiveMatches = 0 
for (x,y) in zip(seqA,seqB):

    if x == y:
        consecutiveMatches += 1 
        reward = 1
        if consecutiveMatches == 2:
           reward = 3;
        if consecutiveMatches > 2 :
           reward = 5;
        if consecutiveMatches > 5 :
           reward = 100;     // jackpot ;-)
        // etc.
        score += reward
    else:
        score -=  1
        consecutiveMatches  = 0

答案 2 :(得分:0)

score = 0
previousMatch == False
for (x,y) in zip(seqa, seqb):
    if x==y && previousMatch:
        score += 3
    elif x==y:
        score += 1
        previousMatch = True
    else:
        score -= 1
        prviousMatch = False

答案 3 :(得分:0)

类似于其他人如何做到这一点,但我宁愿使用像“正确”这样的变量名,而不是在整个地方看到“x == y”......

# Create a list of whether an answer was "correct".
results = [x == y for (x,y) in zip(seqA, seqB)]

score = 0
last_correct = False
for current_correct in results:
    if current_correct and last_correct:
        score += 3
    elif current_correct:
        score += 1
    else:
        score -= 1

    last_correct = current_correct

print score