当前位置: 动力学知识库 > 问答 > 编程问答 >

types - Python - How to know how many kinds of objects there are in a list

问题描述:

a = [1,1,2,2,2,3,3,3,4]

I want answer to be 4 since there are 4 types (1,2,3,4)

Is there any module to do this?

网友答案:

Is this what you want?

In [11]: a=[1,1,2,3,2,4,4,3]

In [12]: c=set(a)

In [13]: len(c)
Out[13]: 4

In [14]: c
Out[14]: set([1, 2, 3, 4])
网友答案:

You can do this with len(set(a)). This puts them into a set, which holds only unique items

a gets collapsed to {1,2,3,4}, which has a length of 4

网友答案:

If you don't want to use len(set(list)) as mentioned above, another way of doing this, although more roundabout; is with a for loop:

listA = [1,1,1,2,2,2,3,3,3,4,4,4]
listB = []
for x in listA:
    if x not in listB:
        listB.append(x)
print listB

This way you have your original list, and a new one that you can do whatever you want without worrying about affecting the original list.

网友答案:

I would try to remove the duplicates using the following. Note that with set, you do not have a defined order.

>>> a = [1,1,2,2,2,3,3,3,4]
>>> print list(set(a))
[1, 2, 3, 4]
>>>
分享给朋友:
您可能感兴趣的文章:
随机阅读: