Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法在Python中计算置换_Python - Fatal编程技术网

无法在Python中计算置换

无法在Python中计算置换,python,Python,我试图找到数字的组合,这里是我已经走了多远,但我不确定我的错误 def perm1(lst): if len(lst) == 0: return [] elif len(lst) == 1: return[lst] else: l = [] for i in range(len(lst)): x = lst[i] xs = lst[:i] + lst[i+1:]

我试图找到数字的组合,这里是我已经走了多远,但我不确定我的错误

def perm1(lst):
    if len(lst) == 0:
        return []
    elif len(lst) == 1:
        return[lst]
    else:
        l = []
        for i in range(len(lst)):
            x = lst[i]
            xs = lst[:i] + lst[i+1:]
        for p in perm1(xs):
            l.append([x]+p)
        return l

data = list('1''2''3''4')
print 'perm1'
for p in perm1(data):
    print p
它打印

perm1
['4', '3', '2', '1']
我的目标是

[1,2] [2,3] [2,4][1,4] ect.

我需要做什么?

我建议使用
itertools.permutations

>>> import itertools
>>> list(itertools.permutations([1,2,3,4],2))
[(1, 2), (1, 3), (1, 4),
 (2, 1), (2, 3), (2, 4),
 (3, 1), (3, 2), (3, 4),
 (4, 1), (4, 2), (4, 3)]

此代码输出两个元素的所有排列:

import itertools

data = ['1','2','3','4']
res = [ [f, l] for f, l in itertools.product(data, repeat=2)]
res
值为:

['1', '2']                                                                                                   
['1', '3']                                                                                                   
['1', '4']                                                                                                   
['2', '1']                                                                                                   
['2', '2']                                                                                                   
['2', '3'] 
(...)

查找itertools的文档

您的问题标题涉及排列。你的问题涉及组合(不是同一件事)。您的示例输出要么是两个集合,要么是一个集合产品(同样,不同的东西)。如果您想要其中任何一项,您可以:

from itertools import product, permutations, combinations
lst = [1,2,3,4]
print product(lst, repeat=2)  #set product
print permutations(lst, 2)  #2-permutations
print combinations(lst, 2)  #2-sets

首先,这不是正确的语法
list('1'2'3'4')
我想你的意思是说
data=[1,2,3,4]
你知道
itertools
库吗?它们有一个函数
itertools.permutations
,可以为您实现这一点。我试图更改语法,但它仍然给出了相同的结果。我不知道intertools库,我在这方面是相当新的。我该怎么用?谢谢大家的帮助。