代码循环输出随机列表问题:如何终止冗余循环并保留条件判断
Hey there! Let's work through this problem to fix the redundant loops and get your expected output.
First, let's break down your requirements again to make sure we're aligned:
- Filter
populationsto getchromosomes: only keep the population where its correspondingscorevalue is ≤avail_res[0] - Select
chromosome_best: pick randomly if there are multiple valid chromosomes, else use the only one (or handle empty cases gracefully) - Extract elements from
q_activewherechromosome_besthas non-zero values - Ensure the code runs once instead of repeating outputs
Why Your Original Code Had Issues
- Redundant loops: Your original code likely wrapped the entire logic in an unnecessary loop (like a
whileor extrafor), causing repeated execution and multiple outputs. - List comprehension error: You tried to use a list comprehension but didn't link
num(fromscore) to its correspondingpopulation—that's why you got a "num undefined" error. We need to pairscoreandpopulationselements together to filter correctly.
Optimized Solution Code
import random # Define your variables as given avail_res = [6, 4] q_active = [2, 3, 4] score = [3, 0, 10, 5] populations = [[1, 0, 0], [0, 0, 0], [0, 1, 1], [0, 0, 1]] # Step 1: Filter populations to get valid chromosomes # Use zip() to pair each score value with its corresponding population chromosomes = [pop for num, pop in zip(score, populations) if num <= avail_res[0]] # Step 2: Select chromosome_best if len(chromosomes) > 1: chromosome_best = random.choice(chromosomes) else: # Handle edge case where no valid chromosomes exist (return empty list) chromosome_best = chromosomes[0] if chromosomes else [] # Step 3: Get elements from q_active where chromosome_best has non-zero values act = [q for idx, q in enumerate(q_active) if chromosome_best[idx] != 0] # Step 4: Print results once print(f"Populations为{chromosomes}") print(f"act为{act}")
Explanation
- Filtering Chromosomes: Using
zip(score, populations)lets us iterate over each score-value and its matching population at the same time. This fixes the "num undefined" error from your original list comprehension. - Selecting Best Chromosome: We check the length of
chromosomes—if there's more than one, we userandom.choice()to pick one; otherwise, we use the only valid entry (or an empty list if none exist). - Extracting Active Elements: We use
enumerate(q_active)to track the index of each element, then match it to the same index inchromosome_bestto check for non-zero values. - Single Execution: This code runs through all steps exactly once, so you'll only get one set of outputs instead of repeated ones.
Note on Your Expected Output
Based on your given variables, the valid chromosomes will be [[1, 0, 0], [0, 0, 0], [0, 0, 1]] (since scores 3, 0, 5 are all ≤ 6). If you want to force the exact expected output of chromosome_best = [1, 0, 0] (and thus act = [2]), you can replace the random selection line with chromosome_best = chromosomes[0].
内容的提问来源于stack exchange,提问作者John Andrei Gayeta
相关产品推荐
相关产品推荐

