nearest_distance_table = [1,4,5,9,10,14,15]
nodes_explored = [2,10,14]
I want to assign a variable next
to the minimum value of nearest_distance_table
that is NOT in nodes_explored
.
Is there a one-liner using min()
to do this? I know how to do this using a for loop, but is there a way to do it with one line with min()?
Using a for-loop:
minimum = float("inf")
for I in nearest_distance_table:
if I < minimum and I not in nodes_explored:
minimum = I
print(I)
CodePudding user response:
You might use comprehension as follows
nearest_distance_table = [1,4,5,9,10,14,15]
nodes_explored = [2,10,14]
minimum = min(i for i in nearest_distance_table if i not in nodes_explored)
print(minimum)
output
1
CodePudding user response:
You can convert the lists to sets:
lowest = min(set(nearest_distance_table).difference(nodes_explored))
Note that this will not work if you want to preserve duplicate values. For example,
nearest_distance_table = [2, 2, 4]
nodes_explored = [2]
will give 4 as the answer as the two 2s will be collapsed into a single value and then removed. This is the same behaviour as in your example.