博客 / 詳情

返回

python 列表元素全排列

題目描述

  • 給定一個列表,對列表元素進行全排列,使得生成一個包含列表的列表,且全排列不能重複,例子:
    輸入:nums = [1,2,3]
    輸出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

實現方式

  • 使用python 自帶的itertools.permutations函數,專門用於生成排列,非常方便。但注意的是permutations 的返回值是元組,不是列表

    點擊查看代碼
    num = [1, 2, 3, 3]
    
    from itertools import permutations
    
    all_permutations = list(list(i) for i in set(permutations(num)))
    print(all_permutations)
    
  • 自己寫代碼實現,使用遞歸,每次將列表中一個元素提取出來,然後讓其他元素全排列,得到全排列的組合後,再將第一個元素插入到全排列的列表中的各個位置,就得到了想要的結果

    點擊查看代碼
    num = [1, 2, 3, 3]
    
    def fullnum(nums):
    	if len(nums) == 0:
    		return None
    	elif len(nums) == 1:
    		return [nums]
    	res = []
    	left = nums[0]
    	right = fullnum(nums[1:])
    	for i in right:
    		for j in range(len(i)+1):
    			result = i[:j] + [left] + i[j:]
    			if result not in res:
    				res.append(result)
    	return res
    print(fullnum(num))
    
user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.