リストが与えられていれば、ある長さのすべての順列がソートされたままになります。Pythonでリストのソートされた順列を得る方法
ので、リストは
[1,1,3,4]
であるならば、長さ2との答えが
[[1,1], [1,1], [1,3], [1,3] [3,4], [1,4], [1,4]]
で効率的な答えを提供してください。
リストが与えられていれば、ある長さのすべての順列がソートされたままになります。Pythonでリストのソートされた順列を得る方法
ので、リストは
[1,1,3,4]
であるならば、長さ2との答えが
[[1,1], [1,1], [1,3], [1,3] [3,4], [1,4], [1,4]]
で効率的な答えを提供してください。
import itertools
l = [1, 1, 3, 4]
r = [perm for perm in itertools.permutations(l, 2) if sorted(perm) == list(perm)]
での結果:
[(1, 1), (1, 3), (1, 4), (1, 1), (1, 3), (1, 4), (3, 4)]
あなたは結果がソートされ、独特の場合:
s = sorted(set(r)) # [(1, 1), (1, 3), (1, 4), (3, 4)]
あなたがリストの代わりにタプルとして結果をしたい場合は、単にlist()
として、それらをキャスト
私はあなたのために、この便利な関数を作った:
def sorted_perms(iterable, r=None):
pool = tuple(sorted(iterable))
n = len(pool)
r = n if r is None else r
for indices in itertools.product(range(n), repeat=r):
if len(set(indices)) == r and tuple_is_sorted(indices):
yield tuple(pool[i] for i in indices)
memo = {} # simple memoization for efficiency.
def tuple_is_sorted(t):
return memo.setdefault(t, bool(sorted(t) == list(t)))
r = list(sorted_perms(l, 2)) # [(1, 1), (1, 3), (1, 4), (1, 3), (1, 4), (3, 4)]
s = sorted(set(r)) # [(1, 1), (1, 3), (1, 4), (3, 4)]
Pythonは実際にすべての順列を実際に計算し、次にすべての順列を削除しますか?それは非効率的ではないですか? –
@ImeanHはい、理論的には非効率ですが、他にどのような良いオプションがありますか? –
@ImeanH答えで私はイエスを与えました、それはそれがすることです、それはOPの質問でした。 –
あなたは
import itertools
import operator
l = [1, 1, 3, 4]
unique = filter(lambda x: operator.le(x[0], x[1]), itertools.permutations(l, 2))
print(sorted(unique))
出力
[(1, 1), (1, 1), (1, 3), (1, 3), (1, 4), (1, 4), (3, 4)]
がリストにそれを変換フィルタリングするitertools.permutationsとoperator.le
を使用することができます
print([[a, b] for a, b in sorted(unique)])
出力
[[1, 1], [1, 1], [1, 3], [1, 3], [1, 4], [1, 4], [3, 4]]
は、なぜあなたは[1,3] '二回が、' [1,1] ''一度だけありますか?重複をどのように扱いたいですか? –
重複を削除したくないのですか?それでは、@Inbarの答えは完璧です。最初に 'set'にキャストするのではなく' sorted(r) 'を実行してください。 –