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],

RaceB =[[ Runner ID, Heart Rate, Kilometers Done,],
[845, 79, 74],
[5363, 86,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],

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.

  • $\begingroup$ 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. $\endgroup$ – gpavanb Jul 24 '17 at 19:13
  • $\begingroup$ 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 :) $\endgroup$ – Jake Clark Jul 25 '17 at 0:28

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.

| cite | improve this answer | |
  • $\begingroup$ 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? $\endgroup$ – Jake Clark Jul 26 '17 at 2:22
  • $\begingroup$ 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. $\endgroup$ – Anon Jul 26 '17 at 5:44
  • $\begingroup$ 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! $\endgroup$ – Jake Clark Jul 27 '17 at 4:07
  • $\begingroup$ 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. $\endgroup$ – Anon Jul 27 '17 at 8:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.