Compare each item in the list with everyone else
Is there a way to compare all the elements of the list (for example, such as [4, 3, 2, 1, 4, 3, 2, 1, 4]) with all the others and return for each element the number of other elements it differs from (ie . for the list above [6, 7, 7, 7, 6, 7, 7, 7, 6])? Then I will need to add numbers from this list.
source to share
li = [4, 3, 2, 1, 4, 3, 2, 1, 4]
from collections import Counter
c = Counter(li)
print c
length = len(li)
print [length - c[el] for el in li]
Creation c
before execution is [length - c[el] for el in li]
better than doing count(i)
for each item i of the list because it means count()
doing the same counting multiple times (every time it encounters a given item, it counts it)
By the way, another way to write:
map(lambda x: length-c[x] , li)
source to share
You can simply use the function sum
along with a generator expression.
>>> l = [4, 3, 2, 1, 4, 3, 2, 1, 4]
>>> length = len(l)
>>> print sum(length - l.count(i) for i in l)
60
The good thing about generator expression is that you don't create an actual list in memory, but functions of the type sum
can still iterate over them and produce the desired result. Note, however, that once you repeat one generator once, you cannot repeat it again.
source to share