简体   繁体   English

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

[英]TypeError: 'int' object does not support item assignment 7

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

This is Python 3 code I wrote to return all the values in a list that occur 'occurrences' times, and display a chosen error message if none were found. 这是我编写的Python 3代码,用于返回列表中出现“发生”次数的所有值,如果未找到,则显示选择的错误消息。 However, this is what I'm getting: 但是,这就是我得到的:

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

I can somewhat tell what the error is, but I'm not sure. 我可以说出什么是错误,但是我不确定。 What I'm trying to do is to have a separate number of occurrences for each different value in the list. 我想做的是为列表中的每个不同值单独设置出现次数。 For example, if I had a list [2,2,5,7,7,7,7,8,8,8] I would want occurrencesFound[2] to end up as 2, occurrencesFound[5] to end up as 1, occurrencesFound[7] to end up as 4, and so on. 例如,如果我有一个列表[2,2,5,7,7,7,7,8,8,8]我会希望epsesionsFound [2]的结果是2,expressionsFound [5]的结果是1,expressionsFound [7]最终为4,依此类推。

With that, the code would then check if any numbers occurred at least the number of times the user asked for, and then return all the numbers that did. 这样,代码随后将检查是否有任何数字至少出现在用户要求的次数之外,然后返回所有数字。 The method I used didn't work great, though... 我使用的方法效果不佳,但是...

What I would like to know is why this is an error and how I might be able to fix it. 我想知道的是为什么这是一个错误以及如何能够修复它。 I tried doing occurrencesFound(curr) instead, and that worked no better. 我尝试改为进行为例,而不是更好。 That was answered in "TypeError: 'function' object does not support item assignment" however. 但是,这在“ TypeError:'功能'对象不支持项目分配”中得到了回答。 Any ideas? 有任何想法吗?

You have occurancesFound set to an integer data type at this line: 您在这行中将enceancesFound设置为整数数据类型:

occurrencesFound = 0

You cannot assign an item to it because it is an integer. 您不能为其分配项目,因为它是整数。

If you want to assign items to it, make it a dict: 如果要为其分配项目,请使其成为字典:

occurancesFound = {}

You're setting occurrencesFound to an int ( 0 ) and then trying to use it as a list ( occurrencesFound[curr] = 0 ). 您正在将occurrencesFound设置为一个int( 0 ),然后尝试将其用作列表( occurrencesFound[curr] = 0 )。 That is the problem. 那就是问题所在。 If you want to store occurences of different entities in occurrencesFound , use it as follows: 如果要将不同实体的occurrencesFound存储在petitionsFound中,请按以下方式使用它:

occurrencesFound = {}
occurrencesFound[curr] = 0

This will create a dictionary of count (int) variables, where curr is the key. 这将创建一个计数(int)变量的字典,其中curr是关键。

As others have mentioned there's a serious inconsistency in your code: you are trying to use occurrencesFound both as an integer and a list. 正如其他人提到的那样,您的代码中存在严重的不一致之处:您试图同时使用作为所有对象和列表使用的occurrencesFound

The simple way to find groups of duplicate items in a list is to use the standard module function itertools.groupby . 查找列表中重复项的组的简单方法是使用标准模块功能itertools.groupby Your find_duplicates takes an errorMessage arg, but I advise that it's cleaner to do the error handling in the calling code rather than in the function that finds the groups. 您的find_duplicates一个errorMessage arg,但是我建议在调用代码中而不是在查找组的函数中进行错误处理是更干净的方法。

My find_duplicates collects the groups in a dict , which is more flexible that using a list , since it can be used for various types of elements, not just integers. 我的find_duplicates收集dict的组,这比使用list更灵活,因为它可以用于各种类型的元素,而不仅仅是整数。 And even if you're just collecting groups of integers, a dict is still better than a list , unless those integers are guaranteed to be roughly contiguous, with the lowest integer near zero (and non-negative). 即使您仅收集整数组, 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)

output 输出

{8: 3, 7: 4}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM