1

大家好,这是我编程的第一年,我从 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
4

6 回答 6

5

使用 aset()代替:

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)
于 2012-12-06T17:23:08.170 回答
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 循环:

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
于 2012-12-06T17:23:00.703 回答
1
stor == True

你实际上并没有设置storTrue这里。

于 2012-12-06T17:25:57.120 回答
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在外循环之外进行初始化。这在两行之后再次完成。
  • 在内部循环中考虑 a 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)

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

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

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

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

于 2012-12-06T17:39:40.297 回答
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)
于 2012-12-06T17:34:39.033 回答
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

这是一种比你的老师正在寻找的更棒的方法(尽管这种方法效率低下)。

于 2012-12-06T17:24:01.643 回答