[英]Replacing items in a list in all possible permutations
Let's say I have a list or an array of the type: 假设我有一个列表或类型的数组:
mylist = [1, 2, 3, 4]
And I want to replace an item in this list. 我想替换此列表中的一个项目。 Normally I would use something like the following:
通常,我会使用类似以下的内容:
mylist[2] = 7
That works well. 那很好。 However, can someone explain how to create all possible permutations of
mylist
when replacing one or more items in mylist
. 然而,有人可以解释如何创建的所有可能的排列
mylist
更换一个或多个项目时mylist
。 For example, I want to create the following: 例如,我要创建以下内容:
[7, 2, 3, 4]
[7, 7, 3, 4]
[7, 2, 7, 4]
[7, 7, 7, 4]
[7, 2, 3, 7]
...(and so on)
I know I can use itertools
to generate all possible permutations, but how can I specify that I want to substitute an item in all possible locations in the list before generating the permutations? 我知道我可以使用
itertools
生成所有可能的排列,但是如何指定要在生成排列之前替换列表中所有可能位置中的项目? Here is how I tried to use itertools
: 这是我尝试使用
itertools
:
list(itertools.permutations([1,2,3,4,7], 4))
This doesn't work because it doesn't substitute 7
more than one time per permutation, and it also generates permutations that do not include the number 7
. 这是行不通的,因为它不会在每个排列中多次替换
7
次,并且还会生成不包含数字7
排列。
Use itertools.combinations
to find the indices to replace: 使用
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)
Output: 输出:
[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]
You can create a function and just pass the list and value to that function and you get what you want : 您可以创建一个函数,然后将列表和值传递给该函数,您将获得所需的内容:
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))
output: 输出:
[[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.