私はMySQLデータベースから一連の行を返すpythonプログラムと関数を持っています。これらの返された行は、タプルに含まれるIDのセットによってフィルタリングされます。次に、itertoolsとlist comprehensionを使用して、固定された制約のセットに適合する「組み合わせ」を形成します(各組み合わせの属性は、 "all equal"そのすべてのユニークな ")。動的制約数に対するitertoolsの組み合わせのフィルタリング
異なる数のIDに対して関数を動的にしたいのですが、返された行を動的にフィルタリングする方法がわかりません(入れ子にされたIF文を混乱させることなく)。 len(tuple_of_ids)に対して動的にするために、以下の関数のif /と条件を書き直す方法はありますか?
私はPython /コード開発に関してはまだ覚えていますので、助けていただければ幸いです!
私の現在(psuedo-)コード:
import itertools
def get_valid_combinations(tuple_of_ids):
data = get_filtered_data_from_database(valid_ids=tuple_of_ids)
# (row1, row2, row3) assumes that the tuple_of_ids has len=3. If tuple_of_ids had 4 members I'd need (row1, row2, row3, row4) etc
valid_combinations = [(row1, row2, row3) for row1, row2, row3 in list(itertools.combinations(data, 3))
if ((row1.Age == row2.Age) # All items in combination have same Age
and (row2.Age == row3.Age))
and ((row1.School != row2.School)
and (row2.School != row3.School)
and (row1.School != row3.School)) # All items in combination have different School
]
# ...etc (i.e. there may be multiple filtering criteria, but always either ("all equal" or "all different")
return valid_combinations
ids_to_search_for = ('C00001', 'C00002', 'C00003')
get_valid_combinations(tuple_of_ids = ids_to_search_for)
>>> [(<database_row_object_1>, <database_row_object_2>, <database_row_object_3>), (<database_row_object_x>, <database_row_object_y>, <database_row_object_z>),...]
代わりのフィルタリングに追加することを忘れないでくださいする必要があることです* SQLクエリ*で、データベースをフィルタリングする必要がありますか? –
それ以外の場合は、 'all()'と 'any()'関数を見てください。 –
組み合わせを1回だけ繰り返し実行する場合は、効率を犠牲にする 'list(combination) 'を使わないでください。 –