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

Trying to add duplicates within a list of lists in order

I have two separate lists within a list.. I am trying to count duplicates within the second list. I can do it from list a to list b, with the result:

count_list = [['about', 1], ['almost', 1], ['apple', 1], ['break', 1], ['Singapore', 1], ['cider', 1], ['up', 1], ['day', 1]]
first_proc_count = [['turn', 1], ['there', 1], ['pear', 1], ['up', 1], ['XXXXXX', 0], ['drink', 1], ['near', 1], ['up', 1]]

for word in first_proc_count:  
    for word2 in count_list:
        if word[0] == word2[0]:
            word[1] = word[1] + word2[1]
            word2[1] = 0  


print(count_list)
print(first_proc_count)

with the result
-[[‘about’, 1], [‘almost’, 1], [‘apple’, 1], [‘break’, 1], [‘Singapore’, 1], [‘cider’, 1], [‘up’, 0], [‘day’, 1]]
-[[‘turn’, 1], [‘there’, 1], [‘pear’, 1], [‘up’, 2], [‘XXXXXX’, 0], [‘drink’, 1], [‘near’, 1], [‘up’, 1]]

with the word “up” being added to 2nd list and “up” being set to 0 in the first.

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

But I am having a problem doing the same within the second list ie. with a single list. I know I should increment the loop by one and look in the incremented loop. The result I would hope for is:

[[‘turn’, 1], [‘there’, 1], [‘pear’, 1], [‘up’, 3], [‘XXXXXX’, 0], [‘drink’, 1], [‘near’, 1], [‘up’, 0]]

I have tried a range and length with an += 1 but I’m getting nowhere. First ever question here. Excuse the bad formatting. Thanks.

>Solution :

Currently the problem is that you’re comparing the list to itself twice over. The following code should fix this:

count_list = [['about', 1], ['almost', 1], ['apple', 1], ['break', 1], ['Singapore', 1], ['cider', 1], ['up', 1], ['day', 1]]
first_proc_count = [['turn', 1], ['there', 1], ['pear', 1], ['up', 1], ['XXXXXX', 0], ['drink', 1], ['near', 1], ['up', 1]]

for i in range(len(first_proc_count)):
    for word2 in first_proc_count[i + 1:]:
        if first_proc_count[i][0] == word2[0]:
            first_proc_count[i][1] = first_proc_count[i][1] + word2[1]
            word2[1] = 0

print(count_list)
print(first_proc_count)
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