重复功能,添加

时间:2014-03-02 23:26:03

标签: python function duplicates

您好我正在尝试开发一个函数来查找列表中的重复项。下面是我到目前为止获得的代码。我似乎无法弄清楚如何让代码正确添加重复数字的数量。

import collections

myList = [5, 9, 14, 5, 2, 5, 1]

def find_duplicates(aList, target):
    if target not in aList:
        print (target, "occurred 0 times")
    else:
        n=0
        print (target, "occurred",n+1,"times")  

代码的输出显示:

find_duplicates(myList, 5)
5 occurred 1 times

显然我错过了程序正确追踪价值发生次数的东西?有人可以帮忙吗?

我不允许使用内置函数的count()或sort()。

3 个答案:

答案 0 :(得分:0)

要仅计算重复次数,只需迭代列表,比较每个值。如果找到匹配项,则递增计数器,而不是报告计数器。为了使这更好,我会返回计数然后打印到def。之外的控制台。

import collections

def find_duplicates(aList, target):
    n = 0
    for obj in aList:
        if obj is target:
            n += 1
    return n



myList = [5, 9, 14, 5, 2, 5, 1]
target = 5
num_dup = find_duplicates(myList, target)
print (target, "occurred", num_dup, "times")

这应该反映出来:

5 occurred 3 times

或者这样做(使用list.count(x)):

myList = [5, 9, 14, 5, 2, 5, 1]
target = 5
num_dup = myList.count(target)
print (target, "occurred", num_dup, "times")

这应该反映出来:

5 occurred 3 times

答案 1 :(得分:0)

您忘记在代码中增加n,因此它始终打印 1 。我认为您的代码应如下所示:

import collections

myList = [5, 9, 14, 5, 2, 5, 1]

def find_duplicates(aList, target):
    if target not in aList:
        print (target, "occurred 0 times")
    else:
        n= aList.count(5)
        print (target, "occurred",n,"times")  

不使用count并从shell中读取目标:

import collections

myList = [5, 9, 14, 5, 2, 5, 2]

def find_duplicates(aList, target):
    result = 0
    for item in aList:
        if item == target:
            result += 1    
    return result

try:
    target = int(raw_input("Choose a number to find duplicates: ")) # for python 3.X use input instead of raw_input
    res = find_duplicates(myList, target)
    print (target, " occurred ", res, " times")
except:
    print("Write a number, not anything else")

这适用于整数,如果你想使用浮点数,只需更改int(...)的{​​{1}}

答案 2 :(得分:0)

这是使用字典的简单案例。请检查以下代码:

def frequency(l):
    counter = {}
    for x in l:
        counter[x] = counter.get(x, 0) + 1

    return counter

它将迭代列表,将每个元素保存为计数器字典的键。注意特殊形式counter.get(x, 0),如果x已经在dict上,它将返回counter [x]的值,否则它将返回零。

检查结果是使用的问题:

print(frequency(myList))
>>> {9: 1, 2: 1, 5: 3, 14: 1, 1: 1}

您可以通过检查字典来获取任何成员的出现次数:

frq = frequency(myList)
print(frq[14])
>>> 1

print(frq[1])
>>> 1

当然可以写一个包装器:

def target_frequencty(target, my_list):
    frq = frequencty(my_list)
    return frq.get(target, 0)

享受。