PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, December 11, 2022

[FIXED] How to find duplicates in list of lists?

 December 11, 2022     list, python, sorting, syntax     No comments   

Issue

I have a list of key binds in a class like so:

self.key_bind_list = [["A", "B"], ["C"], ["SHIFT", "NUM6", "NUM7"], ["A", "B"], ["A", "B", "C"]]

*in this case a duplicate should be detected by the sublists ["A", "B"], but not by ["A", "B"] and ["A", "B", "C"]

And I'd like to check if there are any duplicates on the main list (assuming that the keys within each sublist are uniques, order is not important, and I don't need to know which ones that aren't unique)

I've tried using the set method in the following:

if(len(self.key_bind_list) != len(set(self.key_bind_list))):

Which gave me a unhashable type: 'list' error.


Solution

Assuming you just want to check if there are duplicates, and print out which sublists contain duplicates, you could use an approach with a list that contains set elements, such as so:

key_bind_list = [["A", "B"], ["C"], ["SHIFT", "NUM6", "NUM7"], ["B", "A"], ["A", "B", "C"]]

seen = []

for i, sublist in enumerate(key_bind_list):
    s = set(sublist)
    if s in seen:
        print(f'index {i}: there are duplicates in {sublist}')
    seen.append(s)

Output:

index 3: there are duplicates in ['B', 'A']

To just return a bool value if any sublist in a list is a duplicate (regardless of order) of another sublist, you could do something like this:

def has_duplicates(L: list[list]) -> bool:
    seen = []

    for sublist in L:
        s = set(sublist)
        if s in seen:
            return True
        seen.append(s)

    return False


print(has_duplicates(key_bind_list))


Answered By - rv.kvetch
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing