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.

+3


source to share


4 answers


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)

      

+3


source


You can get a similar counter using the method count()

.
And subtract the total.
Do it on the same line as the list of concepts.



>>> l = [4, 3, 2, 1, 4, 3, 2, 1, 4]
>>> [ len(l)-l.count(i) for i in l ]
[6, 7, 7, 7, 6, 7, 7, 7, 6]

      

+2


source


For Python 2.7:

test = [4, 3, 2, 1, 4, 3, 2, 1, 4]
length = len(test)
print [length - test.count(x) for x in test]

      

+1


source


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.

0


source







All Articles