[英]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
所以我的問題是如何自動化我的 for 循環以在n
更改時打印結果。
您可以通過定義一個以n
為參數的 function 來概括這一點:
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)
Output:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.