簡體   English   中英

Python 排列跳過重復

[英]Python permutations skipping duplicates

我的問題是:我有一個值列表

model = ["AT","V","AP","RH"]

我想生成它們的排列而不重復。

在這種情況下對我來說的排列是例如

["AT"]
["V"]
["AP"]
["RH"]
["AT","V"]
["AT","AP"]
....
["AT","V","AP"]
["AT","V","RH"]
....
["AT","V","AP","RH"]

在這種情況下沒有重復意味着訂單對我來說無關緊要

["AT","V"] == ["V","AT"] is the same for me
["AT","V","AP","RH"] == ["RH","AT","V","AP"] == ["AP","RH","AT","V"] is the same for me

知道如何以聰明的方式實現我的目標嗎?

我找到了一些解決方案,例如 itertools.permutations 但它實際上對我不起作用,因為它沒有考慮我希望忽略“重復項”

您可以將itertools.chain.from_iterableitertools.combinations一起使用。 itertools.combinations將生成給定大小的所有組合。 為了獲得所有所需的組合,我們遍歷所有可能的尺寸。 然后,我們使用itertools.chain.from_iterable ,它將所有組合收集到一個扁平的可迭代對象中:

list(chain.from_iterable(combinations(model, i) for i in range(1, len(model) + 1)))

這輸出:

[('AT',), ('V',), ('AP',), ('RH',),
...
('AT', 'AP', 'RH'), ('V', 'AP', 'RH'), ('AT', 'V', 'AP', 'RH')]
from more_itertools import powerset

list(powerset(["AT","V","AP","RH"]))

#[(),
 ('AT',),
 ('V',),
 ('AP',),
 ('RH',),
 ('AT', 'V'),
 ('AT', 'AP'),
 ('AT', 'RH'),
 ('V', 'AP'),
 ('V', 'RH'),
 ('AP', 'RH'),
 ('AT', 'V', 'AP'),
 ('AT', 'V', 'RH'),
 ('AT', 'AP', 'RH'),
 ('V', 'AP', 'RH'),
 ('AT', 'V', 'AP', 'RH')]

[list(x) for x in powerset(["AT","V","AP","RH"])][1:]  # omitting the blank value

[['AT'],
 ['V'],
 ['AP'],
 ['RH'],
 ['AT', 'V'],
 ['AT', 'AP'],
 ['AT', 'RH'],
 ['V', 'AP'],
 ['V', 'RH'],
 ['AP', 'RH'],
 ['AT', 'V', 'AP'],
 ['AT', 'V', 'RH'],
 ['AT', 'AP', 'RH'],
 ['V', 'AP', 'RH'],
 ['AT', 'V', 'AP', 'RH']]

我想你想要itertools.combinations而不是itertools.permutations

permutations(p[, r])
  r-length tuples, all possible orderings, no repeated elements

combinations(p, r)
  r-length tuples, in sorted order, no repeated elements

這是一個例子:

import itertools


def combos(elements):
    return [
        combo
        for i in range(len(elements))
        for combo in itertools.combinations(elements, i + 1)
    ]


model = ["AT", "V", "AP", "RH"]


combos(model)

# [('AT',),
#  ('V',),
#  ('AP',),
#  ('RH',),
#  ('AT', 'V'),
#  ('AT', 'AP'),
#  ('AT', 'RH'),
#  ('V', 'AP'),
#  ('V', 'RH'),
#  ('AP', 'RH'),
#  ('AT', 'V', 'AP'),
#  ('AT', 'V', 'RH'),
#  ('AT', 'AP', 'RH'),
#  ('V', 'AP', 'RH'),
#  ('AT', 'V', 'AP', 'RH')]

https://docs.python.org/3/library/itertools.html#itertools.combinations

暫無
暫無

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

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