如何获取numpy数组l的最小值及对应q,调整输出格式
Let's adjust your code to meet both of your expected output requirements. Here's the modified version with clear explanations:
import numpy as np # Avoid `from numpy import *` to keep namespace clean # Initialize variables to track the smallest l value and its matching q min_l = 1e10 min_q = None for i in range(1, 4): r = np.random.uniform(0, 3, i) x = np.random.uniform(0, 9, i) h = np.random.uniform(0, 1, i) l = h * 10 # Simplify q assignment with vectorized logic q = np.where(l < 1.0, r, x) # Print each l/q pair on a new line with the loop's i label for l_val, q_val in zip(l, q): print(f"l= {l_val:.11f} q= {q_val:.11f} #for i={i}") # Update the global minimum if current l has a smaller value current_smallest_l = l.min() smallest_index = l.argmin() if current_smallest_l < min_l: min_l = current_smallest_l min_q = q[smallest_index] # Print the final minimum result in your desired format print(f"min is= [{min_l:.8f}] [{min_q:.8f}]")
Key Adjustments Made:
Line-by-line output with i labels:
Instead of printing entire arrays in one line, we loop through eachlandqelement pair withzip(l, q), adding the#for i={i}suffix to every line to mark which loop iteration the element belongs to. Formatted strings ensure consistent decimal precision matching your example.Single-element minimum output:
We no longer store full arrays for tracking the minimum. Instead, we usel.min()to find the smallest value in the currentlarray, thenl.argmin()to get its index—this lets us pull the exact matchingqelement. The final print statement outputs only these two single values in your requested format.Cleaner logic:
Replaced messyif/elifchecks withnp.where()for vectorized q assignment (works better with NumPy arrays), and switched to explicitimport numpy as np(standard practice to avoid namespace conflicts).
Sample expected output (values vary due to randomness):
l= 4.98648387414 q= 4.96850590047 #for i=1 l= 6.22734941766 q= 2.50807065862 #for i=2 l= 8.30807062837 q= 6.36351958551 #for i=2 l= 6.55113742501 q= 6.58695963821 #for i=3 l= 8.91180674608 q= 0.04603165391 #for i=3 l= 1.62449083617 q= 6.79113942876 #for i=3 min is= [1.62449084] [6.79113943]
内容的提问来源于stack exchange,提问作者David

