簡體   English   中英

獲取python中列表的所有排列而沒有重復?

[英]Get all permutations of a list in python without duplicates?

我正在嘗試編寫一個獲取一組字符串的腳本-

["ab", "ls", "u"]

然后創建它們的所有可能組合,但不一定使用所有它們。 我希望上述示例的可能輸出為:


ab
ab ls
ab ls u
ab u ls
ab u

ls
ls ab
ls ab u
ls u ab
ls u

u
u ls
u ls ab
u ab ls
u ab

我的腳本刪除了它所做的其他事情:

stuff = ["ab", "ls", "u"]

for subset in itertools.permutations(stuff):
    concat = ""
    for part in subset:
        concat = concat + part

    #the rest of my script now uses this data

它返回:

ablsu
abuls
lsabu
lsuab
uabls
ulsab

我如何讓它返回我想要的?

您可以一起使用組合和排列。 這應該能讓你繼續前進

a = ["ab", "ls", "u"]
for i in range(1, len(a)+1):
    for comb in combinations(a, i):
        for perm in permutations(comb):
            print(perm)

輸出:

('ab',)
('ls',)
('u',)
('ab', 'ls')
('ls', 'ab')
('ab', 'u')
('u', 'ab')
('ls', 'u')
('u', 'ls')
('ab', 'ls', 'u')
('ab', 'u', 'ls')
('ls', 'ab', 'u')
('ls', 'u', 'ab')
('u', 'ab', 'ls')
('u', 'ls', 'ab')

您可以隨心所欲地處理comb

當您給出包含 3 個元素排列的列表時,會返回包含所有 3 個元素的結果。 您需要提供 1 個元素才能在輸出中獲得ab / ls / u 您需要提供 2 個元素才能在輸出中獲得ab ls / ab u

因此,您可以通過使用列表中的 1/2 元素調用它來使用相同的程序。

stuff = ["ab", "ls", "u"]

for subset in itertools.permutations(stuff):
    concat = ""
    for part in subset:
        concat = concat + part

    #the rest of my script now uses this data

stuff = ["ab", "ls"]

for subset in itertools.permutations(stuff):
    concat = ""
    for part in subset:
        concat = concat + part


stuff = ["ls", "u"]

for subset in itertools.permutations(stuff):
    concat = ""
    for part in subset:
        concat = concat + part

stuff = ["ab", "ls", "u"]
final_list = []
for subset in itertools.permutations(stuff):
    concat = ""
    for part in subset:
        concat = concat + part
        final_list.append(concat)

print(final_list)

['ab',
 'abls',
 'ablsu',
 'ab',
 'abu',
 'abuls',
 'ls',
 'lsab',
 'lsabu',
 'ls',
 'lsu',
 'lsuab',
 'u',
 'uab',
 'uabls',
 'u',
 'uls',
 'ulsab']
import itertools

stuff = ["ab", "ls", "u"]

for i in range(len(stuff) + 1):
    for x in itertools.permutations(stuff[:i]):
        print(x)

但是這個解決方案顯示了所有排列::

()
('ab',)
('ab', 'ls')
('ls', 'ab')
('ab', 'ls', 'u')
('ab', 'u', 'ls')
('ls', 'ab', 'u')
('ls', 'u', 'ab')
('u', 'ab', 'ls')
('u', 'ls', 'ab')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM