简体   繁体   中英

Many to Many data-structure in python

I was wondering how I could implement a many-to-many relationship data-structure. Or if something like this already exists in the wild.

What I would need is two groups of objects, where members from one group are relating to multiple members of the other group. And vice versa. I also need the structure to have some sort of consistency, meaning members without any connections are dropped, or basically cannot exist.

I have seen this answer (it involves SQL-lite database), but I am not working with such huge volumes of objects, so it's not an appropriate answer for this context Many-to-many data structure in Python

Depending on how big your dataset is, you could simply build all possible sets and then assign booleans to see whether the relationship exists.

itertools.combinations

can be of help to generate all possible combinations. Consistency can then be added by checking if any connections are True for each value.
I do not claim this is the prettiest approach, but it should work on smaller datasets.

https://docs.python.org/2/library/itertools.html#itertools.combinations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM