计算列表中不同的数字数量的Python

2024-04-20 08:45:30 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,伙计们,这是我第一年编程,我从python开始。我对编程的理解相当好,但是我需要帮助来回答这个家庭作业问题。在

我必须使用一个列表作为参数,然后返回列表中不同值的数目。问题中的示例列表是[1, 4, 1, 7, 6, 1, 4, 3],因此返回值应该是5。在

现在我知道我解决这个问题的方法可能不简洁或优雅,但如果有人能帮助我,告诉我要改变什么,使之有效,我将不胜感激。在

def count(mylist):
    newlist = []
    newlist.append(mylist[0])
    stor = False
    for i in mylist:
        stor = False
        for j in newlist:
            if j == i:
                stor == True
        if not stor:
            newlist.append(i)
    return newlist

Tags: infalse示例列表for参数if编程
3条回答

使用^{}代替:

def count(myList):
    return len(set(myList))

一个集合将只保存每个值的一个副本,因此将列表转换为集合有一个方便的副作用,即删除所有重复项。结果集的长度就是您要寻找的答案。在

{a2也是最有效的方法:

^{pr2}$

因为它将为与键相关联的值保留空间,所以效率稍低。在

如果只想使用列表(效率最低),请使用not in负成员身份测试:

def count(myList):
    unique = []
    for item in myList:
        if item not in unique:
             unique.append(item)
    return len(unique)

首先,你的程序的一个固定版本

def count(mylist):
    newlist = []
    newlist.append(mylist[0])
    stor = False
    for i in mylist:
        stor = False
        for j in newlist:
            if j == i:
                stor = True # stor == True test for equality
        if not stor:
            newlist.append(i)
    return len(newlist) # you do not want the list itself but its length

这里有一些建议:

  • 不需要在外循环外初始化stor。两行之后再做一次。在
  • 考虑在内部循环中使用break,这样可以加快速度(不需要进行不必要的比较)
  • newlist可以初始化为空列表,而不附加第一项。算法保持有效(内循环第一次迭代次数为零)

下面是代码示例:

^{pr2}$

更优雅(和pythonic):使用in-语法;)

def count(mylist):
    newlist = []
    for i in mylist:
        if i not in newlist:
            newlist.append(i)
    return len(newlist)

基本上,item in something_iterable返回true,如果item可以在something_iterable中找到。大多数项目集合都是iterable(例如列表、集合、字符串。。。'a' in 'abc'返回true)

最具Python式的方式,但没有for/while循环:

def count(mylist):
    return len(set(mylist))

请查阅其他答案以获得解释。在

您可以在此处使用集合:

In [1]: lis=[1, 4, 1, 7, 6, 1, 4, 3]

In [2]: len(set(lis))
Out[2]: 5

关于set的帮助:

^{pr2}$

使用for循环:

In [6]: def count(lis):
   ...:     mylis=[]
   ...:     for elem in lis:
   ...:         if elem not in mylis:  # append the element to
                                       # mylis only if it is not already present
   ...:             mylis.append(x)
   ...:     return len(mylis)        
   ...: 

In [7]: count(lis)
Out[7]: 5

再看一下^{},它返回dict的子类,其中包含元素被重复的次数:

In [10]: from collections import Counter

In [11]: c=Counter(lis)

In [12]: c
Out[12]: Counter({1: 3, 4: 2, 3: 1, 6: 1, 7: 1})

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

相关问题 更多 >