は、ここでの連続した要素を回避R長の組み合わせのための一般的なソリューションです。適切に短いリストのすべてのインデックスcombinationsを取得し、各組み合わせのインデックスを展開します。たとえばr = 3の場合、任意の組み合わせ(x、y、z)は使用インデックスx + 0、y + 1、z + 2に変わります。 R = 2
from itertools import combinations
def non_consecutive_combinations(lst, r):
return [tuple(lst[j+i] for i, j in enumerate(combi))
for combi in combinations(range(len(lst)-r+1), r)]
デモ:R = 3
>>> non_consecutive_combinations([1, 2, 3, 4, 5], 2)
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
デモ:
>>> non_consecutive_combinations([1, 2, 3, 4, 5, 6, 7], 3)
[(1, 3, 5), (1, 3, 6), (1, 3, 7), (1, 4, 6), (1, 4, 7), (1, 5, 7), (2, 4, 6), (2, 4, 7), (2, 5, 7), (3, 5, 7)]
だけペアの簡略化されたバージョン:
>>> [(lst[i], lst[j+1]) for i, j in combinations(range(len(lst)-1), 2)]
[(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)]
'consecutive'手段リストの中で隣り合っているか、直後の数字であるか、自然な麻痺ers? – thefourtheye
@thefourtheyeご協力いただきありがとうございます。連続して私はリストの中でお互いに隣り合っていました。リストは数字ではないかもしれませんが、私は視覚化が容易だと考えました。私はそれをクリアするために質問に何かを追加します。 – faviouz
'itertools'で必要な機能を選択してください:https://docs.python.org/2/library/itertools.htmlそれらをフィルタリングしなければならないかもしれません。 –