Python: Comparing 2D arrays and Returning independent values from those arrays [closed]

I'm sure this would be a common question, however yet to find an answer for.

Suppose I have two, 2D vectors in Python

RaceA =[[ Runner ID, Heart Rate, Kilometers Done,],
[1234, 67, 50],
[1256, 83,64],
[1356,92,82],
[845,80,18]]

RaceB =[[ Runner ID, Heart Rate, Kilometers Done,],
[845, 79, 74],
[5363, 86,34],
[1256,84,53],
[12233,93,74],
[4233,40,34]]


As you can see, both races had different racers. I'd like to compare the heart rates of racers who ran both of the races.

Hence my answer would be:

[[Racer ID, Heart Rate A, Heart Rate B],
[1256,83,84],
[845,80,79]]


I've used the '&' operator and that returns me the racers IDs for example. But I feel like I'm missing out on a function that will return me heart rate values for both racers in a swift fashion.

This obviously isn't my problem (I have vectors 6000 and 50000 rows long) but the premise is there.

• This question is more appropriate for StackOverflow. Also, if you are alright with using pandas, then the ix method along with the & should solve this for you. – gpavanb Jul 24 '17 at 19:13
• I'll look in to pandas and the ix function. Thanks for your help and I'll submit further questions like this over on StackOverflow :) – Jake Clark Jul 25 '17 at 0:28

1 Answer

One liner:

[[ x[0], x[1], y[1] ] for x in RaceA for y in RaceB if x[0] == y[0]]


However for such big lists (not vectors) this might be a bit slow. If you aim for performance, there are better ways to do it probably.

• It seems like this may do it, but wouldn't this return a shaping error as Race A has 4 competitors and Race B has 5? – Jake Clark Jul 26 '17 at 2:22
• There is no error, as you are independently iterating over the two lists, thus each for cycle stops when there are no more elements in the list. If you have troubles understanding what it does, write a single for cycle and have it print the x at each iteration. – Anon Jul 26 '17 at 5:44
• Thank-you for your answer. I've just started learning Python this week and what you've stated has been a great help. This solution works just how I wanted it too. I'm surprised this solution doesn't pop up in scientific and data analysis lectures as this is solution is handy for a whole range of tasks. Thanks again Anon! – Jake Clark Jul 27 '17 at 4:07
• Glad I've helped. A couple more comments. First, my code is just two for cycles condensed in one line, for cycles are explained everywhere. This particular way of writing them is called list comprehension, google it for more info. Second, in data analysis and scientific applications usually people use other data structures (numpy arrays, pandas dataframes etc), which have built-in tools to achieve similar things faster. Lists are basic Python, and are seldom used in these fields, but if you just started it's fine. – Anon Jul 27 '17 at 8:59