0

this is maybe a silly question but I know that must exist a more efficient way how to use a loop in this scenario to create a list that later on I will be able to iterate to compare values.

I have a bunch of r and q, I want to compose a list with these to later compare the values in sort of key values. Please ideas:

here is my code:

r1 = "a"
r2 = "b"
r3 = "c"
r4 = "d"
r5 = "e"

q1 = "a"
q2 = "b"
q3 = "c"
q4 = "d"
q5 = "e"

l = []
record1 = {"q": q1, "r": r1}
record2 = {"q": q2, "r": r2}
record3 = {"q": q3, "r": r3}
record4 = {"q": q4, "r": r4}
record5 = {"q": q5, "r": r5}

l.append(record1)
l.append(record2)
l.append(record3)
l.append(record4)
l.append(record5)

score = 0
for i in l:
    if i['q'] == i['r']:
        score +=1

print(score)
Andres Urrego Angel
  • 1,842
  • 7
  • 29
  • 55

1 Answers1

0

According to Ami Marowka Article on Parallel software, list comprehension is approximately 2 times faster than normal loops

new_list = [expression(i) for i in old_list if filter(i)] 

And an example by Wes McKinney in Python for Data Analysis shows that numpy arrays are 10 - 100 times faster than nested loops like you have in your code above. Both numpy and list comprehension are equally useful to learn and hope this helps.

tcratius
  • 525
  • 6
  • 15