简体   繁体   中英

check identical for list in list(python)

I want to check if there is no identical entries in a list of list. If there are no identical matches, then return True, otherwise False.

For example:

[[1],[1,2],[1,2,3]]  # False
[[1,2,3],[10,20,30]] # True

I am thinking of combine all of the entries into one list, for example: change [[1,2,3][4,5,6]] into [1,2,3,4,5,6] and then check

Thanks for editing the question and helping me!

>>> def flat_unique(list_of_lists):
...     flat = [element for sublist in list_of_lists for element in sublist]
...     return len(flat) == len(set(flat))
... 
>>> flat_unique([[1],[1,2],[1,2,3]])
False
>>> flat_unique([[1,2,3],[10,20,30]])
True

We can use itertools.chain.from_iterable and set built-in function.

import itertools

def check_iden(data):
    return len(list(itertools.chain.from_iterable(data))) == len(set(itertools.chain.from_iterable(data)))

data1 = [[1],[1,2],[1,2,3]]

data2 = [[1,2,3],[10,20,30]]    

print check_iden(data1)

print check_iden(data2)

Returns

False
True

您可以使用具有交集方法的集合来查找哪些元素是常见的

Place all elements of each sublist into a separate list. If that separate list has any duplicates (call set() to find out), then return False . Otherwise return True .

def identical(x):
    newX = []
    for i in x:
        for j in i:
            newX.append(j)
    if len(newX) == len(set(newX)): # if newX has any duplicates, the len(set(newX)) will be less than len(newX)
        return True
    return False

I think you can flat the list and count the element in it, then compare it with set()

import itertools
a = [[1],[1,2],[1,2,3]] 
b = [[1,2,3],[10,20,30]]

def check(l):
    merged = list(itertools.chain.from_iterable(l))
    if len(set(merged)) < len(merged):
        return False
    else:
        return True


print check(a)  # False
print check(b)  # True

Depending on your data you might not want to look at all the elements, here is a solution that returns False as soon as you hit a first duplicate.

def all_unique(my_lists):
    my_set = set()
    for sub_list in my_lists:
        for ele in sub_list:
            if ele in my_set:
                return False
            my_set.add(ele)
    else:
        return True

Result:

In [12]: all_unique([[1,2,3],[10,20,30]])
Out[12]: True

In [13]: all_unique([[1],[1,2],[1,2,3]])
Out[13]: False

Using this method will make the boolean variable "same" turn to True if there is a number in your list that occurs more than once as the .count() function returns you how many time a said number was found in the list.

li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
same = False
for nbr in li:
    if li.count(nbr) > 1:
        same = True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM