首頁 >後端開發 >Python教學 >如何在 Python 中產生排列?

如何在 Python 中產生排列?

Linda Hamilton
Linda Hamilton原創
2024-12-24 04:58:31894瀏覽

How Can I Generate Permutations in Python?

使用Python 庫產生排列

要在Python 中產生清單的所有排列,一種方便的方法是利用itertools.permutations 函數標準庫。例如:

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

排列的自訂實作

或者,您可以建立自訂實作來計算排列:

def permutations(elements):
    if len(elements) <= 1:
        yield elements
        return
    for perm in permutations(elements[1:]):
        for i in range(len(elements)):
            yield perm[:i] + elements[0:1] + perm[i:]

其他方法

如果您如果您願意,您也可以探索以下方法:

# Using reversed indices
def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = range(n)
    cycles = 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

# Using product
def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)

以上是如何在 Python 中產生排列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn