在Python中,有没有一种方法可以从列表中获得所有3对或n对列表?
例如list = 1,2,3,4
结果:[1,2,3,3,4,1,2,4]
我想从Python列表中找到所有可能的n对列表。我不想导入任何其他函数,比如itertools。
发布于 2019-03-22 11:31:54
您可以使用模块itertools。它默认安装在Python中(你不需要通过第三方模块安装它):
>>> import itertools
>>> print(itertools.permutations([1,2,3,4], 3))
[(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 4), (1, 4, 2), (1, 4, 3), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 1, 2), (3, 1, 4), (3, 2, 1), (3, 2, 4), (3, 4, 1), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2)]此itertools.permutations(iterable, r=None)生成给定可迭代元素(如列表)的所有可能排列。如果未指定r或为None,则r默认为可迭代的长度,并生成所有可能的全长排列。
如果您只查找排列的n pair,而不是所有可能的排列,只需删除其余的:
>>> print(list(itertools.permutations([1,2,3,4], 3))[:3])
[(1, 2, 3), (1, 2, 4), (1, 3, 2)]正如您在注释中所要求的,您可以在不导入任何模块的情况下做到这一点。itertools.permutations只是一个函数,您可以自己制作:
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = list(range(n, n-r, -1))
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return但我强烈建议您导入它。如果你不想导入整个模块,这个函数只需执行from itertools import permutations即可。
https://stackoverflow.com/questions/55292411
复制相似问题