Reputation: 365
I have two lists of list that look like this:
List_1 = [[10.7,7.2],[6.3,5.0],[8.9,10.0]]
List_2 = [[10.7,6.8],[6.3,4.9],[8.9,12.7]]
I want to create a third list called List_3 that contains only the pairs of List_2 where the second value of the pairs in List_2 is larger than the second value of the pairs in List_1. For example, in this case List_3 would be a list that looked like this:
List_3 = [[8.9,12.7]]
Because the second value 12.7 is the only one larger than the second value of the pairs in List_1. In other words, I want to compare all the lists inside List_1 with all the lists inside List_2 and only grab the lists inside List_2 where n of List_1 is larger than n of List_2 where Lists 1 and 2 look like:
[[m,n],[m,n],[m,n]]
I tried creating the following code but it is not working as expected:
List_3 = []
for i in range(len(List_2)):
for j in range(len(List_1)):
if List_2[i][1] > List_1[j][1]:
List_3.append(List_2[i][1])
print(List_3)
How could I approach this problem so that I can create List_3 whenever n in List_2[m][n] is larger than List_1[m][n]?
Any ideas or suggestions on how to approach this would be greatly appreciated.
Upvotes: 2
Views: 3114
Reputation: 2331
To modify your existing code:
List_1 = [[10.7,7.2],[6.3,5.0],[8.9,10.0]]
List_2 = [[10.7,6.8],[6.3,4.9],[8.9,12.7]]
List_3 = []
for i in range(len(List_2)):
if List_2[i][1] > List_1[i][1]:
List_3.append(List_2[i])
print(List_3)
What you were doing was looping over all the j
values - ie the indexes for the 2nd values in List_2
for each 2nd value (at index [i][1]
) in List_1. If I understand you correctly, you want to compare only those in the same position in both lists, not every 2nd value in the second list with every 2nd value in the first?
Thus, you only need to loop over one of the lists, and compare that 2nd value in each sublist with it's respective value in the first list (they'll be the same index, i
, so that keeps things simple).
NB This will only work for lists of equal length.
Upvotes: 1
Reputation: 2159
Try this one:
List_1 = [[10.7,7.2],[6.3,5.0],[8.9,10.0]]
List_2 = [[10.7,6.8],[6.3,4.9],[8.9,12.7]]
List_3=[]
for i ,j in zip(List_1,List_2):
if i[1]<j[1]:
List_3.append(j)
print (List_3)
Upvotes: 1
Reputation: 362716
Use a list comprehension and a zip
:
>>> List_1 = [[10.7,7.2],[6.3,5.0],[8.9,10.0]]
... List_2 = [[10.7,6.8],[6.3,4.9],[8.9,12.7]]
...
>>> List_3 = [l2 for l1, l2 in zip(List_1, List_2) if l2[1] > l1[1]]
>>> List_3
[[8.9, 12.7]]
Upvotes: 7