# 在Python中生成集合的所有排列

2021年4月21日18:47:38 发表评论 756 次浏览

``````# Python function to print permutations of a given list
def permutation(lst):

# If lst is empty then there are no permutations
if len (lst) = = 0 :
return []

# If there is only one element in lst then, only
# one permuatation is possible
if len (lst) = = 1 :
return [lst]

# Find the permutations for lst if there are
# more than 1 characters

l = [] # empty list that will store current permutation

# Iterate the input(lst) and calculate the permutation
for i in range ( len (lst)):
m = lst[i]

# Extract lst[i] or m from the list.  remLst is
# remaining list
remLst = lst[:i] + lst[i + 1 :]

# Generating all permutations where m is first
# element
for p in permutation(remLst):
l.append([m] + p)
return l

# Driver program to test above function
data = list ( '123' )
for p in permutation(data):
print p``````

``````['1', '2', '3']
['1', '3', '2']
['2', '1', '3']
['2', '3', '1']
['3', '1', '2']
['3', '2', '1']``````

``````from itertools import permutations
l = list (permutations( range ( 1 , 4 )))
print l``````

``[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]``