简体   繁体   中英

Count different numbers in list python

Hey guys so this is my first year programming and I started with 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.

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:

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:

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:

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(iterable) -> new set object
Build an unordered collection of unique elements.

using a for-loop:

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:

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

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.

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. This is done two lines later again.
  • consider a break in the inner loop - this speeds things up a bit (no unneeded comparison)
  • newlist can be initialized to an empty list without appending the first item. 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 ;)

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 . Most collection of items is iterable (eg lists, sets, strings ... 'a' in 'abc' returns true )

and the most pythonic way but without for/while-loops:

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

Please look into other answers for an explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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