有两个元素的组合

有两个元素的组合

本文介绍了有两个元素的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python.可以使用此方法对列表中的元素进行置换:

With python.It's possible to permute elements in a list with this method:

def perms(seq):
    if len(seq) <= 1:
        perms = [seq]
    else:
        perms = []
        for i in range(len(seq)):
            sub = perms(seq[:i]+seq[i+1:])
            for p in sub:
                perms.append(seq[i:i+1]+p)

return perms

如果列表是:seq = ['A','B','C'],则结果将是..

if a list is: seq = ['A', 'B', 'C'], the result will be..

[[''A','B','C'],['A','C','B'],['B','A','C'],['B' ,'C','A'],['C','A','B'],['C','B','A']]

[['A', 'B', 'C'], ['A', 'C', 'B'], ['B', 'A', 'C'], ['B', 'C', 'A'], ['C', 'A', 'B'], ['C', 'B', 'A']]

如何修改此方法,以便一次排列两个词?我的意思是,如果列表是:seq = ['A','B','C'].我想收到[['A','B'],['A','C'],['B','C'].

HOW TO modify this method, to make permutations two terms a time?I mean, if the list is: seq = ['A', 'B', 'C']. I wanna receive [['A', 'B'], ['A', 'C'], ['B', 'C'].

我做不到.我正在尝试,但不能.感谢您的帮助.

I can't do it. I'm trying but I can't. Thanks for the help.

推荐答案

考虑在Python的itertools模块中使用combinations函数:

Consider using the combinations function in Python's itertools module:

>>> list(itertools.combinations('ABC', 2))
[('A', 'B'), ('A', 'C'), ('B', 'C')]

这就是说的:给我所有来自序列'ABC'的两个元素的组合.

This does what it says: give me all combinations with two elements from the sequence 'ABC'.

这篇关于有两个元素的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:50