我正在尝试获取由4个元素组成的列表的可能组合,例如:('E', 'J', 'M', 'Z')
,有效组合的条件是更改每个组合中所有4个元素的位置
可能的组合有:
('J', 'E', 'Z', 'M')
('M', 'Z', 'E', 'J')
('Z', 'M', 'J', 'E').....
我尝试了itertools.permutations(('E', 'J', 'M', 'Z'), 4)
,结果一点也不令人满意。有人能帮忙吗?
import itertools
def get_permutations_whose_all_elems_are_in_a_different_place_than_the_original(original_elems):
for permutation in itertools.permutations(original_elems):
if any(left == right for left, right in zip(permutation, original_elems)):
continue
else:
yield permutation
initial_list = ('E', 'J', 'M', 'Z')
print(str(initial_list) + "n--------------------")
solutions = get_permutations_whose_all_elems_are_in_a_different_place_than_the_original(initial_list)
print("n".join(str(solution) for solution in solutions))
输出:
('E', 'J', 'M', 'Z')
--------------------
('J', 'E', 'Z', 'M')
('J', 'M', 'Z', 'E')
('J', 'Z', 'E', 'M')
('M', 'E', 'Z', 'J')
('M', 'Z', 'E', 'J')
('M', 'Z', 'J', 'E')
('Z', 'E', 'J', 'M')
('Z', 'M', 'E', 'J')
('Z', 'M', 'J', 'E')
第一列没有E,第二列没有J,第三列没有M,第四列没有Z。