1

This is a follow on from a previous question I asked about populating a new list element-wise based on a condition. I am now wondering if I can create a second new list that is populated still conditionally on the first with list comprehension. Originally I had:

 old_list1 = np.reshape(old_data, (49210, 1)) #Reshape into 1D array
 new_list1 = [None] #Create empty list to be filled
 max_value = np.nanmax(old_list1)
 threshold = 0.75 * max_value #Create threshold to be used as condition for new list.

...then, as per the answer to my previous question, I can create a new list based on threshold as:

new_list1 = [element[0] for element in old_list1 if element[0] > threshold]

I have another list, old_list2, that is the same length as old_list1. Can I create new_list2 using list comprehension that is still conditional on the matching element of old_list1 meeting the threshold condition?

That is, is this:

j = 0
for i in range(len(old_list1)):
    if old_list1[i] > threshold:
         new_list1[j] = old_list[i]
         new_list2[j] = old_list2[i]
         j += 1 

...possible with list comprehension?

Thank you as always!

  • List comprehensions are for only for building lists, but your `for` loop mutates two existing lists, which is not the same thing – Chris_Rands Aug 18 '20 at 13:31

1 Answers1

2

Yes you can. You can either use list comprehension in conjunction with zip to associate the items. Or, if you already have the data in numpy arrays, just use conditional indexing:

import numpy as np

data1 = np.array([10, 1, 9, 8])
threshold = 0.75 * np.nanmax(data1)  # 7.5 in this example

data2 = np.array([500, 200, 300, 100])

# using list comprehension and zip
new_data = [t[1] for t in zip(data1, data2) if t[0] > threshold]
print(new_data)   # [500, 300, 100]

# using numpy's conditional indexing...
new_data2 = data2[data1 > threshold]
print(new_data2)  # [500 300 100]
AirSquid
  • 10,214
  • 2
  • 7
  • 31