简体   繁体   English

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

[英]Count different numbers in list python

Hey guys so this is my first year programming and I started with python. 大家好,这是我第一年编程,我从python开始。 I am understanding the programming fairly well but I need help with this homework question. 我对编程非常了解,但在此作业问题上需要帮助。

I have to use a list as my parameter and then return the number of different values in the list. 我必须使用列表作为我的参数,然后返回列表中不同值的数量。 The example list in the question is [1, 4, 1, 7, 6, 1, 4, 3] and therefore the returned value should be 5. 问题中的示例列表为[1, 4, 1, 7, 6, 1, 4, 3] ,因此返回值应为5。

Now I know my method of solving it is probably not concise or elegant but if someone could help me and tell me what to change so it works I would greatly appreciate it. 现在,我知道我的解决方法可能并不简洁或优雅,但是如果有人可以帮助我并告诉我要进行哪些更改以使其可行,我将不胜感激。

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

Use a set() instead: 使用set()代替:

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

A set will only hold one copy of each value, so converting your list to a set has the handy side-effect of removing all the duplicates. 一组将仅保存每个值的一个副本,因此将列表转换为一组具有删除所有重复项的便捷副作用。 The length of the resulting set is the answer you are looking for. 结果集的长度就是您要寻找的答案。

Using a set is the most efficient method; 使用集合是最有效的方法。 alternatively you could use a dict() too: 或者,您也可以使用dict()

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

which is ever so slightly less efficient because it'll reserve space for the values associated with the keys. 效率稍差一些,因为它将为与键关联的值保留空间。

If all you want to use is a list, (least efficient), use the not in negative membership test: 如果你想用一个列表,(效率最低),使用not in负成员资格测试:

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

you can use sets here: 您可以在这里使用集:

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

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

help on set : 帮助上set

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

using a for-loop: 使用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

Also have a look at collections.Counter() , it returns a sub-class of dict , which contains the number of times an element was repeated: 还可以看看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

If you cannot use set , try 如果无法使用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

This sorts the list and then increments the counter each time an element is unequal to the next one. 这将对列表进行排序,然后在每次元素与下一个元素不相等时递增计数器。


If you can't use sorting, you'd normally keep track of counted values. 如果不能使用排序,通常会跟踪计数值。 That is too obvious though, so here is a funny way to do it without keeping a list of values you already counted: 但是,这太明显了,因此这是一种有趣的方法,无需保留您已经计算在内的值列表:

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

So for [1, 4, 1, 7, 6, 1, 4, 3] , the weights are [1/3, 1/2, 1/3, 1, 1, 1/3, 1/2, 1] which adds up to 5 as it should. 因此,对于[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

This is a much more awesome way than what your teacher is looking for (despite the inefficiency of this method). 这是比您的老师正在寻找的方法更加出色的方法(尽管这种方法效率低下)。

If you are supposed to use a loop, then this is the way(or one of them). 如果您应该使用循环,那么这就是方法(或其中之一)。 :) :)

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)

At first, a fixed version of your program 首先,是程序的固定版本

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

And here some suggestions: 这里有一些建议:

  • you do not need to initialize stor outside the outer loop. 您无需在外部循环外初始化stor This is done two lines later again. 稍后再两行完成此操作。
  • consider a break in the inner loop - this speeds things up a bit (no unneeded comparison) 考虑break内循环的break -这样可以加快速度(无需进行不必要的比较)
  • newlist can be initialized to an empty list without appending the first item. newlist可以初始化为空列表,而无需附加第一项。 The algorithm stays valid (the inner loop have zero iterations the first time) 该算法保持有效(内部循环首次具有零次迭代)

here as code-example: 这里作为代码示例:

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)

And more elegant (and pythonic): use the in -syntax ;) 更优雅(和pythonic):使用in syntax;)

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

Basically item in something_iterable returns true, if item can be found in something_iterable . 如果可以在something_iterable找到item ,则基本上item in something_iterable返回item Most collection of items is iterable (eg lists, sets, strings ... 'a' in 'abc' returns true ) 大多数项目集合都是可迭代的(例如列表,集合,字符串... 'a' in 'abc'返回true)

and the most pythonic way but without for/while-loops: 和最pythonic的方式,但没有for / while循环:

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

Please look into other answers for an explanation. 请查看其他答案以获得解释。

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

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