gpt4 book ai didi

python - 过滤 itertools 组合以获取动态数量的约束

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:55 25 4
gpt4 key购买 nike

我有 python 程序和函数,它从我的 MySQL 数据库返回一系列行。这些返回的行由元组中包含的一组 ID 进行过滤,然后使用 itertools 和列表理解来形成符合一组固定约束的“组合”(每个组合的属性必须是“全部相等”或“在该组合中都是独一无二的)。

我想让该函数针对不同数量的 ID 进行动态处理,但我不确定如何动态过滤返回的行(没有一堆嵌套的 IF 语句)。有没有办法可以重写下面函数中的 if/and 条件,使它们对于 len(tuple_of_ids) 来说是动态的?

在 python/代码开发方面,我仍然是一个学习者,因此我们将不胜感激!

我当前的(伪)代码:

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>),...]

最佳答案

正如 Martijn 在评论中所说,您可以考虑在 SQL 中进行过滤,这肯定会更有效。如果必须在 Python 中完成过滤,则可以使用集合理解轻松完成“全部相等”或“全部不同”检查:

length = len(tuple_of_ids)
valid_combinations = [tup for tup in itertools.combinations(data, length)
if len({r.Age for r in tup}) == 1
and len({r.School for r in tup}) == length]

这样做的唯一开销是集合一旦创建就会被销毁,因为只需要它们的长度。

顺便说一句,您可以将 cast 拖放到 itertools.combinationslist 中,因为您实际上并不需要该列表。

关于python - 过滤 itertools 组合以获取动态数量的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38750858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com