标签:href https ble 排列 方式 怎么 相同 targe head
@
原型 itertools.permutations(iterable, r=None)
返回可迭代对象 iterable 的长度为 r 的所有数学全排列方式(每种排列方式是以元组形式存在)。
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
字典与列表、元组不同,它涉及键和值两个东西,所以要单独说一下
键
的全排列示例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
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
itertools 中的 permutations 实现全排列和任意排列
标签:href https ble 排列 方式 怎么 相同 targe head
原文地址:https://www.cnblogs.com/2944014083-zhiyu/p/14856003.html