Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine python lists, with shared items, into new lists

I am new to python and I hit a roadblock. I have a python list that contains a single list on each line. Basically, I would like to combine lists that share values among lists. For example, below is what my python list looks at the moment and what I would like the data to look like after the additional commands are executed.

I know this sort of problem is ideal for sets and intersections, but I just haven't been able to get them to work correctly. I have also seen a post using indexes and that hasn't worked for me either.

What the list looks like:

[
    ['mary', 'home'],
    ['mary', 'school'],
    ['mary', 'work'],
    ['bob', 'home'],
    ['bob', 'school'],
    ['bob', 'work'],
    ['tom', 'work'],
    ['tom', 'school'],
    ['tom', 'home'],
    ['bill', 'vacation'],
]

What I want it to look like:

[
    ['mary', 'bob', 'tom', 'home', 'school', 'work'],
    ['bill', 'vacation'],
]
like image 288
owen Avatar asked Apr 23 '26 12:04

owen


1 Answers

Your example data suggests that order is important in your input data, which would complicate the situation. Assuming that it's actually just an example and order isn't important, sets are indeed an ideal way to solve the problem:

data = [
    ['mary', 'home'],
    ['mary', 'school'],
    ['mary', 'work'],
    ['bob', 'home'],
    ['bob', 'school'],
    ['bob', 'work'],
    ['tom', 'work'],
    ['tom', 'school'],
    ['tom', 'home'],
    ['bill', 'vacation'],
]

combined = []

for subset in [set(d) for d in data]:
    for candidate in combined:
        if not candidate.isdisjoint(subset):
            candidate.update(subset)
            break
    else:
        combined.append(subset)

This uses Python's for-else construct, which not everyone is familiar with. combined will contain a list of sets, so you might want to convert them to lists depending on your use case.

like image 193
Zero Piraeus Avatar answered Apr 25 '26 08:04

Zero Piraeus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!