如何自动实现嵌套循环以生成mⁿ行的全唯一组合表格?
Manually writing nested loops works for fixed values of n, but it's tedious to adjust the code every time n changes. Instead, we can leverage Python's built-in tools or a custom iterative approach to create a fully flexible solution. Here's how to do it:
Using itertools.product (Simplest Approach)
Python's itertools.product is designed specifically to generate Cartesian products—exactly what we need for all possible state combinations. It eliminates the need for any manual loop nesting.
Solution Code
import itertools def generate_state_combinations(m, n): # Generate all n-length tuples of values from 1 to m all_combinations = itertools.product(range(1, m + 1), repeat=n) # Print each combination as a space-separated string for combo in all_combinations: print(' '.join(map(str, combo))) # Test with your examples print("=== m=2, n=3 ===") generate_state_combinations(2, 3) print("\n=== m=2, n=4 ===") generate_state_combinations(2, 4)
How It Works
itertools.product(range(1, m+1), repeat=n)creates every possible tuple of lengthnwhere each element is between 1 andm(matching your original output's 1-based numbering).- We convert each tuple to a space-separated string for printing, just like your manual loop examples.
- If you need to store the combinations instead of printing them, convert the product object to a list:
list(itertools.product(...)).
Verified Output
For m=2, n=3, the output will match your example exactly:
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2
Bonus: No External Libraries (Custom Iterative Approach)
If you can't use itertools, you can build combinations incrementally without recursion:
def generate_state_combinations(m, n): # Start with all 1-length combinations combinations = [[num] for num in range(1, m + 1)] # Build up to n-length combinations for _ in range(n - 1): new_combos = [] for combo in combinations: for num in range(1, m + 1): new_combos.append(combo + [num]) combinations = new_combos # Print each combination for combo in combinations: print(' '.join(map(str, combo)))
This works by starting with single-element lists, then repeatedly appending each possible value to existing combinations until we reach the desired length n.
内容的提问来源于stack exchange,提问作者sohrab haghayegh

