Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Counting number of elements less than and adding it to the original in Python

I have two lists I1 and I2. I am comparing elements of I2 to elements in I1 and want to add the number of elements which are less than or equal to it. For example, 11 in I2 has two two elements less than or equal to it in I1. Hence, 2 should be added to 11. Similarly, for elements 27 and 41 in I2. I present the current and expected output.

I1=[1,11,13,16,26,30,43,46]

I2=[11,27,41]
I2=[i for i in I2 if I2<=I1]
print("I2 =",I2)

The current output is

I2 = []

The expected output is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I2 = [13,32,47]

>Solution :

use a counter to see the number and their frequency which is less than current, so to avoid the repetiiton calculation

from collections import Counter

I1=[1,11,13,16,26,30,43,46]
I2=[11,27,41]

c1 = Counter(I1)
result = []

for i in I2:
    val = sum(j for v, j in c1.items() if v<=i) + i
    result.append(val)
print(result) # 13 32 47
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading