大家好,这是我第一年的编程,我是从 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 negative membership test:
def count(myList):
unique = []
for item in myList:
if item not in unique:
unique.append(item)
return len(unique)
