如何仅递归地加入具有共同元素的集合,同时保留所有其他集合不变?
假设我有一个定义如下的集合列表
set_list = [{1, 2}, {2, 3}, {3, 50, 60}, {70, 90}, {70, 80}, {1, 2}, {999, 888}]
我想定义一个函数,该函数接收如上所述的集合列表并输出一个新的集合列表,这样如果上面的列表作为参数传递,则输出将如下 我该
output = [{1, 2, 3, 50, 60}, {70, 80, 90}, {999, 888}]
如何实施这样的事情?
请注意,我使用列表是为了方便(我不关心集合的顺序,但我确实希望输出不包含重复项),因为集合不能是集合的元素。我知道可以用frozensets,但是写起来很麻烦。尽管如此,任何使用 freezesets 或其他方式的实现都会很棒。
Let's say I have a list of sets defined as follows
set_list = [{1, 2}, {2, 3}, {3, 50, 60}, {70, 90}, {70, 80}, {1, 2}, {999, 888}]
I want to define a function that receives a list of sets such as the above and outputs a new list of sets such that if the above list is passed as an argument the output will be as follows
output = [{1, 2, 3, 50, 60}, {70, 80, 90}, {999, 888}]
How can I go about implementing something like this?
Note that I am using a list out of convenience (I don't care about the order of the sets but I do want the output to not contain duplicates) since sets can't be elements of sets. I know I can use frozensets, but it is cumbersome to write. Nevertheless, any implementation using frozensets or otherwise will be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您需要递归解决方案,因此这里有一个使用
frozensets
的递归解决方案 -输出 -
例如,
set_list
中的一个集合与output
中的多个集合匹配代码> -输出 -
Since you wanted a recursive solution, here's a recursive solution using
frozensets
-output -
For an example case when a set in
set_list
matches with multiple sets inoutput
-output -
我不确定这是否是最好的方法,但可能会有所帮助。
输出:
编辑:
正如 Max Miller 指出的那样,这对于某些输入不起作用,他的解决方案更加完整。
I'm not sure if this is the best way to do it, might help nevertheless.
Output:
Edit:
As Max Miller pointed out, this does not work for certain inputs, his solution is much more complete.