繁体   English   中英

在列表python中计算不同的数字

[英]Count different numbers in list 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

使用set()代替:

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

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

使用集合是最有效的方法。 或者,您也可以使用dict()

def count(myList):
     return len(dict.fromkeys(myList))

效率稍差一些,因为它将为与键关联的值保留空间。

如果你想用一个列表,(效率最低),使用not in负成员资格测试:

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

您可以在这里使用集:

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

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

帮助上set

set(iterable) -> new set object
Build an unordered collection of unique elements.

使用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

还可以看看collections.Counter() ,它返回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
stor == True

您实际上不是在这里将stor设置为True

如果无法使用set ,请尝试

def count(mylist):
    mylist.sort()
    total = 0
    for k in range(1, len(mylist) -1 ):
        if mylist[k] != mylist[k + 1]:
            total += 1
    return total

这将对列表进行排序,然后在每次元素与下一个元素不相等时递增计数器。


如果不能使用排序,通常会跟踪计数值。 但是,这太明显了,因此这是一种有趣的方法,无需保留您已经计算在内的值列表:

def count(mylist):
    total = 0
    for k, value in enumerate(mylist):
        total += 1 / mylist.count(value)
    return total

因此,对于[1, 4, 1, 7, 6, 1, 4, 3] 1、4、1、7、6、1、4、3 [1, 4, 1, 7, 6, 1, 4, 3] ,权重为[1/3, 1/2, 1/3, 1, 1, 1/3, 1/2, 1]总计应为5

这是比您的老师正在寻找的方法更加出色的方法(尽管这种方法效率低下)。

如果您应该使用循环,那么这就是方法(或其中之一)。 :)

the_list = [1, 4, 1, 7, 6, 1, 4, 3]

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

首先,是程序的固定版本

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内循环的break -这样可以加快速度(无需进行不必要的比较)
  • newlist可以初始化为空列表,而无需附加第一项。 该算法保持有效(内部循环首次具有零次迭代)

这里作为代码示例:

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

更优雅(和pythonic):使用in syntax;)

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

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

和最pythonic的方式,但没有for / while循环:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM