简体   繁体   中英

How to compare the elements of one list with those of two others and generate an output for every element in python?

I tried to create a function with two "for loops" to compare the elements of two lists and generate an output for each comparison, but my output is always 0.

What is wrong with my code?

UserInput = ["A", "B", "A"]

CorrectAnswers = ["A", "B", "B"]
FalseAnswers = ["B", "A", "A"]

def run():
    score = 0
    for i in UserInput:
        for z in CorrectAnswers:
            if i is z:
                score = score + 1
            elif i is not z:
                for p in FalseAnswers:
                    if p is x:
                        score = score - 1
            else:
                raise ValueError("Invalid Input")
    print(score)

run()
        
    

Thanks a lot in advance...and please don't decry me again.

I'm assuming you want to compare 2 arrays element wise.

Maybe you should try something like this:

for index, val in enumerate(UserInput): 
   if val == CorrectAnswers[index]:
      'do something'
   else:
      'do something else'

be aware that you might have a case where len(UserInput) > len(CorrectAnswers) you have to catch that case before you enter the for loop

run function

def run(user_input, answers): score = 0

for user_answer_index, user_answer in enumerate(user_input):  # looping over the value and the index (enumerate)
    try:  
        if user_answer == answers[user_answer_index]:  # if the answers are the same 
            score += 1
            
    except IndexError:  # index error 
        print("index error")

print(score)

main function

def main():

# data 
user_input = ["A", "B", "A"]
correct_answers = ["A", "B", "B"]

run(user_input, correct_answers)

main()

Part of the issue with your original code is that you reference "x" but it isn't assigned. I modified your code more than intended but you it looked like you wanted to use the enumerate() function where you can create an index based one one list and use it reference that same position in another list.

def run():
    score = 0
    for i, j in enumerate(UserInput):
            if j == CorrectAnswers[i]:
                score = score+1        
            elif j == FalseAnswers[i]:
                score = score-1
            else:
                raise ValueError("Invalid Input")
    return(score)   
print(run())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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