seini
seini

Reputation: 151

Combining list to a list of lists, where matches are in same list inside the list

I have two lists, and I want to combine them into a list where the object in the list is a list of matches between the two lists, but also include objects that do not match.

I am a bit lost on where to even start to get this result as I am a python novice.

The two lists:

husband = ['cat','dog','bunny']
wife = ['dog','bunny','horse']

The result I want:

farm = [['cat'],['dog','dog'],['bunny','bunny'],['horse']]

Upvotes: 0

Views: 58

Answers (5)

cdlane
cdlane

Reputation: 41872

Sounds like a problem for groupby:

from itertools import groupby

husband = ['cat', 'dog', 'bunny']
wife = ['dog', 'bunny', 'horse']

farm = [list(group) for _, group in groupby(sorted(husband + wife))]

print(farm)

OUTPUT

% python3 test.py
[['bunny', 'bunny'], ['cat'], ['dog', 'dog'], ['horse']]
%

Upvotes: 0

Red
Red

Reputation: 27567

Here is how you can use the collections module:

from collections import Counter

husband = ['cat','dog','bunny']
wife = ['dog','bunny','horse']

farm = Counter(husband+wife) # Counter({'dog': 2, 'bunny': 2, 'cat': 1, 'horse': 1})
farm = [[k]*farm[k] for k in farm]

print(farm)

Output:

[['cat'], ['dog', 'dog'], ['bunny', 'bunny'], ['horse']]

Upvotes: 1

sushanth
sushanth

Reputation: 8302

Here are couple of way's using collections module,

from collections import Counter,defaultdict

husband = ['cat','dog','bunny']
wife = ['dog','bunny','horse']

print([[k] * v for k , v in Counter(husband + wife).items()])

#or

farm = defaultdict(list)
for v in husband + wife:
    farm[v].append(v)

print(farm.values())

Upvotes: 1

bigbounty
bigbounty

Reputation: 17368

Using sets

In [25]: husband = ["cat","dog","bunny"]
    ...: wife = ["dog","bunny","horse"]

In [26]: husband_set = set(husband)

In [27]: wife_set = set(wife)

In [28]: data = []

In [29]: data.extend([[i] * 2 for i in wife_set.intersection(husband_set)])

In [30]: data.append([i for i in husband_set.difference(wife_set)])

In [31]: data.append([i for i in wife_set.difference(husband_set)])

In [32]: data
Out[32]: [['dog', 'dog'], ['bunny', 'bunny'], ['cat'], ['horse']]

Upvotes: 1

vestronge
vestronge

Reputation: 962

full_l = husband + wife
unique_l = list(dict.fromkeys(full_l))
# unique list with order preserved,  if you dont want to preserve order, you can just use set(full_l)
output = [[animal] * full_l.count(animal) for animal in unique_l]

Upvotes: 2

Related Questions