Python 设置(过滤)重复

Python 设置(过滤)重复,python,python-3.x,Python,Python 3.x,我维护一套需要根据各种条件逐步缩小的设备 例如: acceptable = read_input() acceptable.rank_by_x() acceptable = set(filter(is_rank_x_top_100, acceptable)) acceptable.rank_by_y() acceptable = set(filter(is_rank_y_top_10, acceptable)) 它可以工作,但是集合(filter())构造看起来很难看。有更好的方法吗?或者,只

我维护一套需要根据各种条件逐步缩小的设备

例如:

acceptable = read_input()
acceptable.rank_by_x()
acceptable = set(filter(is_rank_x_top_100, acceptable))
acceptable.rank_by_y()
acceptable = set(filter(is_rank_y_top_10, acceptable))

它可以工作,但是
集合(filter())
构造看起来很难看。有更好的方法吗?或者,只需将set子类化,就可以添加一个具有相同功能的方法吗?

您可以将其折叠为:

acceptable = set()
#...
acceptable = set(filter(is_rank_y_top_10,
                        filter(is_rank_x_top_100, acceptable)))
或使用理解:

acceptable = set()
#...
acceptable = set(i for i in acceptable
                 if is_rank_x_top_100(i) and is_rank_y_top_10(i))
acceptable = {i for i in acceptable if is_rank_x_top_100(i)}

您可以将其折叠为:

acceptable = set()
#...
acceptable = set(filter(is_rank_y_top_10,
                        filter(is_rank_x_top_100, acceptable)))
或使用理解:

acceptable = set()
#...
acceptable = set(i for i in acceptable
                 if is_rank_x_top_100(i) and is_rank_y_top_10(i))
acceptable = {i for i in acceptable if is_rank_x_top_100(i)}

如果您使用的是Python 3或Python 2.7,则可以使用集合理解:

acceptable = set()
#...
acceptable = set(i for i in acceptable
                 if is_rank_x_top_100(i) and is_rank_y_top_10(i))
acceptable = {i for i in acceptable if is_rank_x_top_100(i)}

如果您使用的是Python 3或Python 2.7,则可以使用集合理解:

acceptable = set()
#...
acceptable = set(i for i in acceptable
                 if is_rank_x_top_100(i) and is_rank_y_top_10(i))
acceptable = {i for i in acceptable if is_rank_x_top_100(i)}

你知道列表的理解吗?过滤器是列表理解的特例。如果x==y,[x代表x,x代表x]会产生一个所有x都是y的列表。@Wes:这会让它更难看
set([x表示x在可接受的情况下是热的(x)]
@KennyTM
#…
根据当前的
可接受的状态进行各种计算,其结果会影响将来调用的函数。我的例子不清楚,所以我重写它。你知道列表的理解吗?过滤器是列表理解的特例。如果x==y,[x代表x,x代表x]会产生一个所有x都是y的列表。@Wes:这会让它更难看
set([x表示x在可接受的情况下是热的(x)]
@KennyTM
#…
根据当前的
可接受的状态进行各种计算,其结果会影响将来调用的函数。我的例子不清楚,所以我正在重写它。