TypeError:' int'对象不支持项目分配7

时间:2016-04-11 16:03:31

标签: python arrays typeerror

def find_duplicates(inputList, occurrences, errorMessage):
    '''find_duplicates(inputList, occurrences) -> Finds and returns all duplicates in list l
    which occur at least 'occurrences' times
    If none are found then errorMessage is returned'''
    curr = 0
    prev = 0
    occurrencesFound = 0
    duplesFound = []
    inputList = sorted(inputList)
    print(inputList)
    for i in range(len(inputList)):
        prev = curr
        curr = inputList[i]
        occurrencesFound[curr] = 0
        if curr == prev and duplesFound.count(curr) == 0:
            occurrencesFound[curr] += 1
            if occurrencesFound[curr] == occurrences:
                duplesFound.append(curr)
                occurrencesFound = 0
    if duplesFound == []:
        duplesFound = errorMessage
    return duplesFound

这是我编写的Python 3代码,用于返回列表中出现的所有值' occurrence'时间,如果没有找到,则显示所选的错误消息。但是,这就是我得到的:

Traceback (most recent call last):
  File "C:\Python\Python Homework.py", line 68, in <module>
    print(find_trivial_taxicab_numbers(3))
  File "C:\Python\Python Homework.py", line 56, in find_trivial_taxicab_numbers
    while find_duplicates(intsFound, (n), "Error") == "Error":
  File "C:\Python\Python Homework.py", line 32, in find_duplicates
occurrencesFound[curr] = 0
TypeError: 'int' object does not support item assignment

我可以稍微说出错误是什么,但我不确定。我想要做的是为列表中的每个不同值分别出现一些事件。例如,如果我有一个列表[2,2,5,7,7,7,7,8,8,8]我希望eventssFound [2]最终为2,occurrencesFound [5]最终为1,occurrencesFound [7]最终为4,依此类推。

然后,代码将检查是否有任何数字至少出现用户要求的次数,然后返回所有数字。我使用的方法并不好用,但是......

我想知道的是为什么这是一个错误,以及我如何能够解决它。我试着改变了eventssFound(curr),而且效果不错。然而,"TypeError: 'function' object does not support item assignment"回答了这个问题。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

您在此行中将occurrence设置为整数数据类型:

occurrencesFound = 0

您无法为其指定项目,因为它是一个整数。

如果要为其指定项目,请将其设为dict:

occurancesFound = {}

答案 1 :(得分:0)

您将occurrencesFound设置为int(0),然后尝试将其用作列表(occurrencesFound[curr] = 0)。那就是问题所在。如果要在occurrencesFound中存储不同实体的出现,请按如下方式使用:

occurrencesFound = {}
occurrencesFound[curr] = 0

这将创建count(int)变量的字典,其中curr是关键字。

答案 2 :(得分:0)

正如其他人提到的那样,您的代码存在严重的不一致:您试图将occurrencesFound用作整数和列表。

在列表中查找重复项组的简单方法是使用标准模块函数itertools.groupby。你的find_duplicates需要一个errorMessage arg,但我建议在调用代码中而不是在找到组的函数中进行错误处理更清晰。

我的find_duplicates收集dict中的群组,使用list更灵活,因为它可以用于各种类型的元素,而不仅仅是整数。即使你只是收集整数组,dict仍然优于list,除非这些整数保证大致连续,最小整数接近于零(和非阴性)。

from itertools import groupby

def find_duplicates(input_list, occurrences=2):
    input_list = sorted(input_list)
    groups = {}
    for k, g in groupby(input_list):
        # We have to convert iterator `g` to a list to get its length
        glen = len(list(g))
        if glen >= occurrences:
            groups[k] = glen
    return groups

# Test
input_list = [7, 8, 7, 2, 8, 5, 7, 7, 8, 2]

groups = find_duplicates(input_list, 3)
if not groups:
    print('No groups found')
else:
    print(groups)

<强>输出

{8: 3, 7: 4}