相对python /编程新手在这里。我正在使用itertools permutations方法来缩小产生的结果,使用“if”语句来创建我需要的列表。
在下面的代码中,您将看到我想从排列中返回一个缩小的列表,其中逗号的索引与列表的逗号的索引匹配。但是,此代码仅在我手动将索引放入“if”语句时才有效。由于我不会提前知道我想要列出的列表中有多少逗号,我该如何为此编码呢?
from itertools import permutations
prp1 = ["UP", ",", "DOWN", "LEFT", ",", "RIGHT"]
# grab indices for commas in 'prp1' list
comma_indices = []
for index, p in enumerate(prp1):
if p == ",":
commas.append(index)
perms = permutations(prp1)
lst = []
for perm in perms:
# Presently I have manually inserted the indices of commas,
# but how to do this non-manual for unknown amount of commas here?
if perm[1] == ',' and perm[4] == ',':
lst.append(perm)
for l in lst:
print l
我确实考虑过做这样的事情:
for perm in perms:
for comma in commas:
if...........
..但是我一次只能访问1个逗号。
任何帮助非常感谢, 达伦
编辑:
需要置换的更多示例列表:
prp2 = ['down', ',', 'up', 'left', 'down']
prp3 = ['down', 'down', ',', 'up', ',', 'left', ',', 'right', ',', 'left']
答案 0 :(得分:1)
您已经知道如何在没有硬编码的情况下找到逗号所在的索引:
comma_indices = []
for index, p in enumerate(prp1):
if p == ",":
commas.append(index)
因此,您可以对perm
应用相同的方法,看看它是否匹配,例如
observed_comma_indices = [index for index, p in enumerate(perm) if p == ","]
if comma_indices == observed_comma_indices:
lst.append(perm)
但也有其他方法。例如,您不能生成所有排列,而只保留您想要的排列,而只能在第一时间创建所需的排列:
from itertools import permutations
def permute_some(seq, indices_to_permute):
for perm in permutations(indices_to_permute):
newseq = seq[:]
for i, p in zip(indices_to_permute, perm):
newseq[i] = seq[p]
yield newseq
给出了
>>> seq = ["A", "B", ",", "C", ","]
>>> perm_ii = [i for i,x in enumerate(seq) if x != ","]
>>> for p in permute_some(seq, perm_ii):
... print p
...
['A', 'B', ',', 'C', ',']
['A', 'C', ',', 'B', ',']
['B', 'A', ',', 'C', ',']
['B', 'C', ',', 'A', ',']
['C', 'A', ',', 'B', ',']
['C', 'B', ',', 'A', ',']