如何优化生成相对星号矩阵的冗长Python代码?
Hey there! It’s clear your current code gets the job done, but all those repetitive variable declarations and manual appends are making it messy and hard to maintain. Let’s refactor this to be cleaner, more efficient, and way easier to adjust if you ever need to handle more than 12 values down the line.
Step 1: Simplify Creating the count List
Instead of calling append() 12 times, just initialize the list directly with your 12 values—this cuts out 11 unnecessary lines of code:
# Replace all those appends with a single list initialization count = [count1, count2, count3, count4, count5, count6, count7, count8, count9, count10, count11, count12]
Step 2: Calculate Star Counts Efficiently
No need to declare 12 separate stars variables. We can use a list comprehension to compute all star counts in one go, and we’ll calculate the maximum count just once (recalculating it 12 times in your original code was a waste of resources!):
max_count = max(count) # Generate star counts for all values in a single line stars = [int(num * 10 / max_count) for num in count]
Step 3: Generate Asterisk Strings Without Repetitive Loops
Forget the 12 astericks variables and clunky conditional loop. We can build each asterisk string in one step with another list comprehension. Remember: "*" * n creates a string of n asterisks, and we pad with spaces to hit the 10-character length you need:
# Create each asterisk string efficiently asterisks = ["*" * s + " " * (10 - s) for s in stars]
Full Refactored Code
Putting it all together, here’s the streamlined version that does exactly what your original code does—just way cleaner:
# Initialize count list with your 12 input values count = [count1, count2, count3, count4, count5, count6, count7, count8, count9, count10, count11, count12] max_count = max(count) stars = [int(num * 10 / max_count) for num in count] asterisks = ["*" * s + " " * (10 - s) for s in stars] # Print each line matching your example format for idx in range(12): print(f"{asterisks[idx]} count{idx+1}")
Key Benefits of This Approach
- Less redundancy: No more copying and pasting variable declarations or calculations.
- Better efficiency: We calculate
max(count)once instead of 12 times, and Python’s list comprehensions are optimized to run faster than manual loops with repeated conditionals. - Easier maintenance: If you ever need to handle 15 or 20 values instead of 12, you just update the
countlist—no need to add dozens of new variables or loop conditions.
内容的提问来源于stack exchange,提问作者mana lamo

