How to count different elements in list of lists?

烂漫一生 提交于 2020-02-25 07:11:31

问题


The example is...

>>>list1 = [[1,2,3],[1,2,3],[1,2,2],[1,2,2]]

>>>how_many_different_lists(list1)

>>>2 #They are [1,2,3] and [1,2,2]

How can I make the how_many_different_lists function?

(sorry for the bad English)


回答1:


Here`s working code:

from copy import deepcopy

def how_much_dif_l(arg):
    arg_list=deepcopy(arg)
    i=0
    length=len(arg_list)
    while i<length:
        a = arg_list[i]
        if arg_list.count(a)>1:
            length-=1
            arg_list.remove(a)
        else: 
            i+=1


    return len(arg_list)

list1= [[1,2,3],[1,2,3],[1,2,2],[1,2,2]]
print(how_much_dif_l(list1))



回答2:


If you just need to know how many different lists are there, you could simply do:

def how_many_different_lists(lists):
    s = set(str(list_) for list_ in lists)
    return len(s)

You can call this function as follows:

>>> list1 = [[1,2,3],[1,2,3],[1,2,2],[1,2,2]]
>>> how_many_different_lists(list1)
2



回答3:


lis = [[1, 2, 3], [1, 2, 3], [1, 2, 2], [1, 2, 2]]
import itertools
lis.sort()
print(list(lis for lis,_ in itertools.groupby(lis)))

The above code outputs

[[1, 2, 2], [1, 2, 3]]

You may also do

l = []
for i in lis:
    if i not in l:
        l.append(i)

Or

l = [lis[i] for i in range(len(lis)) if i == 0 or lis[i] != lis[i-1]]


来源:https://stackoverflow.com/questions/59925390/how-to-count-different-elements-in-list-of-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!