在此python列表中,这两个for语句是做什么的?

时间:2019-07-11 16:19:47

标签: python

因此我在Python中遇到了这种算法,该算法会生成一个包含唯一排列列表的列表,给定一个可能包含也可能不包含重复整数的列表。

nums = [1, 2, 1]
def generateUniquePermutations(self, nums):
    perms = [[]]
    for n in nums:
        perms = [p[:i] + [n] + p[i:]
                 for p in perms
                 for i in xrange((p + [n]).index(n) + 1)]
    return perms

我不了解for p列表中嵌入的for iperms循环的语法或它们的用途,特别是因为它们遵循语句{{1 }}会生成一条路径。在这种情况下,是否将{{1}中的p[:i] + [n] + p[i:]视为for i下的nested?看起来很像。

1 个答案:

答案 0 :(得分:1)

此列表理解。它生成一个列表。 例如:

squares = [x ** 2 for x in range(4)]
#[0, 1, 4, 9]
## Equivalent To:
squares = []
for x in range(4):
    squares.append(x ** 2)
#[0, 1, 4, 9]

全部一行是这样的:

perms = [p[:i] + [n] + p[i:] for p in perms for i in xrange((p + [n]).index(n) + 1)]

更长/扩展的方法:

newPerms = []
for i in xrange((p + [n]).index(n) + 1)
   for p in perms:
       newPerms.append(p[:i] + [n] + p[i:])
perms = newPerms