Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I most efficienty check the unique elements in a list?

let's say I have a list

li = [{'q':'apple','code':'2B'},
      {'q':'orange','code':'2A'},
      {'q':'plum','code':'2A'}]

What is the most efficient way to return the count of unique "codes" in this list? In this case, the unique codes is 2, because only 2B and 2A are unique.

I could put everything in a list and compare, but is this really efficient?

like image 552
TIMEX Avatar asked Apr 02 '10 22:04

TIMEX


People also ask

How do you identify unique elements in a list?

array(list) and then use numpy. unique(x) function to get the unique values from the list. numpy. unique() returns only the unique values in the list.

How do I get a list of unique values in Excel?

To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates. To highlight unique or duplicate values, use the Conditional Formatting command in the Style group on the Home tab.


1 Answers

Probably the most efficient simple way is to create a set of the codes, which will filter out uniques, then get the number of elements in that set:

count = len(set(d["code"] for d in li))

As always, I advise to not worry about this kind of efficiency unless you've measured your performance and seen that it's a problem. I usually think only about code clarity when writing this kind of code, and then come back and tighten it only if I've profiled and found that I need to make performance improvements.

like image 196
Eli Courtwright Avatar answered Oct 26 '22 19:10

Eli Courtwright