简体   繁体   中英

Python Count Unique Elements for Multidimensional List

I've written a function to count unique elements in a 2d list in Python, and I'm wondering how to make it more general for lists of any number of dimensions. Answers I've seen so far about finding the dimension by testing if the first instance is a list don't seem robust. Please note I want to avoid using NumPy.

Any suggestions please?

def count_unique_elements_2d_list(list_2d):
    flat_list = []
    for sublist in list_2d:
        for item in sublist:
            flat_list.append(item)

    unique_recipes = set(flat_list)
    return len(unique_recipes)

You can avoid the extra space you have used by running two for loops and adding unique elements to the set only.

def count_unique_elements_2d_list(list_2d):
    unique=set()
    for sublist in list_2d:
        for item in sublist:
            unique.add(item)

    return len(unique)

If the element is already present it would not be added to the set. And you will get the unique count of elements.

This will return on the unique elements, which you can then call len on.

def get_unique(some_array, seen=None):
    if seen is None:
        seen = set()
    for i in some_array:
        if isinstance(i, list):
            seen.union(get_unique(i, seen))
        else:
            seen.add(i)
    return seen

What is happening?
This is a recursive problem. If the level is not a list, then assume it's an item and add it to the set of seen items. if it is a list, then run the function on it again.

Here is my quick hack. It's a little unclean with the except but it's short and relatively efficient.

def get_dimensions(lut):
    dim = 0
    test = lut
    try:
        while test[0]:
            dim = dim + 1
            test = test[0]
    except TypeError:
        return dim

def to_onedimensional(lut, dim, output, counter):
    if(counter == dim - 1):
        for x in lut:
            output.append(x)
    else:
        for x in lut:
            to_onedimensional(x, dim, output, counter + 1)

This is how to use it:

lut = [[[3],[4]], [[2],[3]]]

print(get_dimensions(lut))
output = []
to_onedimensional(lut, get_dimensions(lut), output, 0)
res = set(output)
print(len(res))

Output:

3
3

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