计算列表python中的不同数字

时间:2012-12-06 17:21:17

标签: python list loops

嘿伙计们这是我的第一年编程,我开始使用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

6 个答案:

答案 0 :(得分:5)

改为使用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)

答案 1 :(得分:2)

你可以在这里使用套装:

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

另请查看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

答案 2 :(得分:1)

stor == True

您实际上并未在此stor设置True

答案 3 :(得分:0)

如果您无法使用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/3, 1/2, 1/3, 1, 1, 1/3, 1/2, 1],最多可加5

这比你老师正在寻找的方式更令人敬畏(尽管这种方法效率低下)。

答案 4 :(得分:0)

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

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)

答案 5 :(得分:0)

首先,您的程序的固定版本

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可以初始化为空列表而不附加第一个项目。算法保持有效(内部循环第一次没有迭代)

这里是代码示例:

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 - 语法;)

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

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

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

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

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