Major Redux
Major Redux

Reputation: 103

Finding only pairs in list using list comprehension

Looking for a fancy one line solution to finding pairs of items in a list using list comprehension.

I've got some code that finds multiples, but can't figure out how to split those multiples into pairs.

lst = [1,2,4,2,2,3,3,1,1,1,2,4,3,4,1]
len(set([x for x in lst if lst.count(x) > 1]))

Code above returns 4. Answer should be 6 pairs, [1,1,1,1,1] = 2, [2,2,2,2] = 2, [3,3,3] = 1 and [4,4,4] = 1.

Upvotes: 0

Views: 298

Answers (3)

CristiFati
CristiFati

Reputation: 41112

Another approach would be using [Python 3.Docs]: class collections.Counter([iterable-or-mapping]):

>>> from collections import Counter
>>>
>>> lst = [1, 2, 4, 2, 2, 3, 3, 1, 1, 1, 2, 4, 3, 4, 1]
>>>
>>> c = Counter(lst)
>>> c
Counter({1: 5, 2: 4, 4: 3, 3: 3})
>>>
>>> sum(item // 2 for item in c.values())
6

and the one line equivalent:

>>> sum(item // 2 for item in Counter(lst).values())
6

Upvotes: 3

Nordle
Nordle

Reputation: 2981

You can do the following (if I've understood your pairing method properly):

lst = [1,2,4,2,2,3,3,1,1,1,2,4,3,4,1]
the_dict = {x: int((lst.count(x)/2)) for x in lst}

print(sum(the_dict.values()))

> 6

print(the_dict)

> {1: 2, 2: 2, 4: 1, 3: 1}

This makes a dictionary with the count of all pairs, then you can sum the values in the dictionary to get the pair count. Then you also have the dictionary available with the pair count of each value, if you need it.

Upvotes: 1

shriakhilc
shriakhilc

Reputation: 3000

A one-liner with no other intermediate variables would be:

sum(lst.count(x)//2 for x in set(lst))

It loops over set(lst) which contains all the distinct numbers in lst, and adds their pair counts.

Upvotes: 1

Related Questions