![](/img/trans.png)
[英]Generate all permutations of a list and permutations of the possible lists within that list?
[英]Replacing items in a list in all possible permutations
假設我有一個列表或類型的數組:
mylist = [1, 2, 3, 4]
我想替換此列表中的一個項目。 通常,我會使用類似以下的內容:
mylist[2] = 7
那很好。 然而,有人可以解釋如何創建的所有可能的排列mylist
更換一個或多個項目時mylist
。 例如,我要創建以下內容:
[7, 2, 3, 4]
[7, 7, 3, 4]
[7, 2, 7, 4]
[7, 7, 7, 4]
[7, 2, 3, 7]
...(and so on)
我知道我可以使用itertools
生成所有可能的排列,但是如何指定要在生成排列之前替換列表中所有可能位置中的項目? 這是我嘗試使用itertools
:
list(itertools.permutations([1,2,3,4,7], 4))
這是行不通的,因為它不會在每個排列中多次替換7
次,並且還會生成不包含數字7
排列。
使用itertools.combinations
查找要替換的索引:
replace = 7
mylist = [1, 2, 3, 4]
for i in range(1, len(mylist) + 1):
for selected in itertools.combinations(range(len(mylist)), i):
res = mylist[:]
for n in selected:
res[n] = replace
print(res)
輸出:
[7, 2, 3, 4]
[1, 7, 3, 4]
[1, 2, 7, 4]
[1, 2, 3, 7]
[7, 7, 3, 4]
[7, 2, 7, 4]
[7, 2, 3, 7]
[1, 7, 7, 4]
[1, 7, 3, 7]
[1, 2, 7, 7]
[7, 7, 7, 4]
[7, 7, 3, 7]
[7, 2, 7, 7]
[1, 7, 7, 7]
[7, 7, 7, 7]
您可以創建一個函數,然后將列表和值傳遞給該函數,您將獲得所需的內容:
import itertools
def replaced_it(list_1,value):
final_list = []
len_=len(list_1)
track_index = [k for k, j in enumerate(list_1)]
for i in range(len(track_index) + 1):
empty_list = [value]
replaced_one = list_1[:]
for ia in itertools.permutations(track_index, r=i):
if ia:
for i, j in zip(ia, empty_list * len(ia)):
replaced_one[i] = j
if replaced_one not in final_list:
final_list.append(replaced_one)
replaced_one = list_1[:]
return final_list
print(replaced_it([1,2,3,4],7))
輸出:
[[7, 2, 3, 4], [1, 7, 3, 4], [1, 2, 7, 4], [1, 2, 3, 7], [7, 7, 3, 4], [7, 2, 7, 4], [7, 2, 3, 7], [1, 7, 7, 4], [1, 7, 3, 7], [1, 2, 7, 7], [7, 7, 7, 4], [7, 7, 3, 7], [7, 2, 7, 7], [1, 7, 7, 7], [7, 7, 7, 7]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.