用for循环用n个值解包元组?
Tuple unpacking with n values with for loop?
我正在进行排列,我想以特定方式打印我的结果。
我的代码:
from itertools import permutations as p
n = 3 #This can be change
permu_lst = [i for i in p(range(1, n+1)]
for a, b, c in permu_lst:
print(a, b, c)
Output:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
所以我的问题是如何在 n
更改时自动执行 for 循环以打印结果。
您可以通过定义一个函数来概括这一点 n
:
from itertools import permutations as p
def print_permutations(n):
permu_lst = [i for i in p(range(1, n+1))]
for per in permu_lst:
print(*per)
per
前的 * 解包元组。
使用iterable unpacking operator(*)
from itertools import permutations as p
n = 4 #This can be change
permu_lst = [i for i in p(range(1, n+1))]
for tup in permu_lst:
print(*tup)
输出:
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1
我正在进行排列,我想以特定方式打印我的结果。
我的代码:
from itertools import permutations as p
n = 3 #This can be change
permu_lst = [i for i in p(range(1, n+1)]
for a, b, c in permu_lst:
print(a, b, c)
Output:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
所以我的问题是如何在 n
更改时自动执行 for 循环以打印结果。
您可以通过定义一个函数来概括这一点 n
:
from itertools import permutations as p
def print_permutations(n):
permu_lst = [i for i in p(range(1, n+1))]
for per in permu_lst:
print(*per)
per
前的 * 解包元组。
使用iterable unpacking operator(*)
from itertools import permutations as p
n = 4 #This can be change
permu_lst = [i for i in p(range(1, n+1))]
for tup in permu_lst:
print(*tup)
输出:
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1