itertools 中的 permutations 實現全排列和任意排列


@

原型 itertools.permutations(iterable, r=None)

作用

返回可迭代對象 iterable 的長度為 r 的所有數學全排列方式(每種排列方式是以元組形式存在)。

參數

  • iterable 可迭代對象 列表,元組,字典
  • r 排列的長度,如果 r 未指定或為 None ,r 默認設置為 iterable 的長度,這種情況下,生成所有全長排列。

iterable 是列表,元組示例

import itertools

num=0
a=[1,2,3,4]  #iterable  是列表
for i in itertools.permutations(a,2):
    print(i)
    num+=1
print(num)
import itertools

num=0
a=(1,2,3,4)   #iterable  是元組
for i in itertools.permutations(a,2):
    print(i)
    num+=1
print(num)

輸出都是:

(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 4)
(4, 1)
(4, 2)
(4, 3)
12

iterable 是字典示例

字典與列表、元組不同,它涉及鍵和值兩個東西,所以要單獨說一下

字典的 的全排列示例

import itertools

num=0
a={'a':1,'b':2,'c':3,'d':4}   # iterable  是字典
for i in itertools.permutations(a,3):
    print(i)
    num+=1
print(num)

輸出是鍵的全排列

('a', 'b', 'c')
('a', 'b', 'd')
('a', 'c', 'b')
('a', 'c', 'd')
('a', 'd', 'b')
('a', 'd', 'c')
('b', 'a', 'c')
('b', 'a', 'd')
('b', 'c', 'a')
('b', 'c', 'd')
('b', 'd', 'a')
('b', 'd', 'c')
('c', 'a', 'b')
('c', 'a', 'd')
('c', 'b', 'a')
('c', 'b', 'd')
('c', 'd', 'a')
('c', 'd', 'b')
('d', 'a', 'b')
('d', 'a', 'c')
('d', 'b', 'a')
('d', 'b', 'c')
('d', 'c', 'a')
('d', 'c', 'b')
24

等價於

import itertools

num=0
a={'a':1,'b':2,'c':3,'d':4}   # iterable  是字典
for i in itertools.permutations(a.keys(),2):
    print(i)
    num+=1
print(num)

怎么輸出 字典值 的全排列呢

字典的 的全排列示例

import itertools

num=0
a={'a':1,'b':2,'c':3,'d':4}   # iterable  是字典
for i in itertools.permutations(a.values(),3):
    print(i)
    num+=1
print(num)

輸出

(1, 2, 3)
(1, 2, 4)
(1, 3, 2)
(1, 3, 4)
(1, 4, 2)
(1, 4, 3)
(2, 1, 3)
(2, 1, 4)
(2, 3, 1)
(2, 3, 4)
(2, 4, 1)
(2, 4, 3)
(3, 1, 2)
(3, 1, 4)
(3, 2, 1)
(3, 2, 4)
(3, 4, 1)
(3, 4, 2)
(4, 1, 2)
(4, 1, 3)
(4, 2, 1)
(4, 2, 3)
(4, 3, 1)
(4, 3, 2)
24

排列的長度 r 指定與未指定示例

import itertools

num=0
a=[1,2,3,4]
for i in itertools.permutations(a,4):
    print(i)
    num+=1
print(num)
import itertools

num=0
a=[1,2,3,4]
for i in itertools.permutations(a):
    print(i)
    num+=1
print(num)

上面的輸出都是:

(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)
24

也證明了我說的如果 r 未指定或為 None ,r 默認設置為 iterable 的長度,這種情況下,生成所有全長排列。

注意: 即使元素的值相同,不同位置的元素也被認為是不同的。如果元素值都不同,每個排列中的元素值不會重復。

可迭代對象有元素的值相同示例

import itertools

num=0
a=[1,2,1,4]
for i in itertools.permutations(a,2):
    print(i)
    num+=1
print(num)

輸出

(1, 2)
(1, 1)
(1, 4)
(2, 1)
(2, 1)
(2, 4)
(1, 1)
(1, 2)
(1, 4)
(4, 1)
(4, 2)
(4, 1)
12

更多 itertools 的內容見文檔 https://docs.python.org/zh-cn/3/library/itertools.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM