Count number of distinct items in a list without using a hash table
本问题已经有最佳答案,请猛点这里访问。
假设我有一个列表(不一定要排序):
1 | lst = [1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 10] |
我需要一个返回列表中唯一元素计数的函数,在本例中是
我不能使用
我想做些类似的事情:
1 2 3 4 5 | num = len(lst) for e in lst: for i in lst: if e == i: num -= 1 |
号
但很明显,它不起作用。谢谢!
试试这个:
对列表执行双嵌套循环的任何解决方案在
1 2 3 4 5 6 7 8 | def count_number_unique(my_list): prev = None unique_count = 0 for ele in sorted(my_list): if ele != prev: unique_count += 1 prev = ele return unique_count |
结果:
1 2 3 4 5 6 7 | In [20]: lst = [1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 10] In [21]: count_number_unique(lst) Out[21]: 10 In [22]: count_number_unique([1,2,1,9,1,2]) Out[22]: 3 |
号