Python TypeError:'type'对象不支持项目分配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37758228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python TypeError: 'type' object does not support item assignment
提问by Tang
I have to design and implement a TwoSum
class. It should support the following operations:
我必须设计和实现一个TwoSum
类。它应该支持以下操作:
add
- Add the number to an internal data structure.find
- Find if there exists any pair of numbers which sum is equal to the value.
add
- 将数字添加到内部数据结构中。find
- 查找是否存在总和等于该值的任何一对数字。
Here is my code:
这是我的代码:
class TwoSum(object):
dict = {}
def add(self,n):
dict[n] = n #TypeError: 'type' object does not support item assignment
def find(self,n):
for i in range(0,len(dict)+1):
if dict[i] == None:
continue
val = n - dict[i]
if dict[val] != None and val != i+1:
return True
return False
test = TwoSum()
test.add(1)
test.add(3)
test.add(5)
print(test.find(4)) # True
print(test.find(7)) # False
I got error message
我收到错误信息
TypeError: 'type' object does not support item assignment for "dict[n] = n"
类型错误:“类型”对象不支持“dict[n] = n”的项目分配
Any help or suggestion? Thank you so much!
任何帮助或建议?非常感谢!
采纳答案by Keatinge
Lot of issues here, I'll try to go through them one by one
问题比较多,我会一一尝试
The data structure
数据结构
dict = {}
Not only is this overwriting python's dict, (see mgilson's comment) but this is the wrong data structure for the project. You should use a list instead (or a set if you have unique unordered values)
这不仅覆盖了 python 的 dict,(参见 mgilson 的评论)而且这是项目的错误数据结构。你应该使用一个列表(或者一个集合,如果你有唯一的无序值)
Using the data structure
使用数据结构
The data structure is an instance variable, it needs to be defined with self
and inside the __init__
function. You should be using something like this:
数据结构是一个实例变量,需要self
在__init__
函数内部定义。你应该使用这样的东西:
class TwoSum(object):
def __init__(self):
self.numbers = []
def add
定义添加
def add(self,n):
dict[n] = n
Assigning items to a dictionairy is not the way to do it. You should instead append to your list. Additionally you need to append to the list for that instance using self.variableName = value
将项目分配给字典不是这样做的方法。您应该改为附加到您的列表中。此外,您需要使用self.variableName = value
def find
定义查找
That range is wrong, and you would need a nested range, or itertools.combinations since you have to check for any two numbers that sum to a certain value, pythons sum()
is handy here.
该范围是错误的,您需要一个嵌套范围或 itertools.combinations,因为您必须检查总和为某个值的任意两个数字,pythonssum()
在这里很方便。
To loop through the numbers you can use two ranges or itertools.combinations
要遍历数字,您可以使用两个范围或 itertools.combinations
The code
编码
import itertools
class TwoSum(object):
def __init__(self):
self.numbers = []
def add(self, num):
self.numbers.append(num)
def find(self, desiredSum):
for nums in itertools.combinations(self.numbers, 2):
if sum(nums) == desiredSum:
return True
return False
test = TwoSum()
test.add(1)
test.add(3)
test.add(5)
print(test.find(4))
print(test.find(7))
#True
#False
Def find without itertools
没有 itertools 的定义查找
def find(self, desiredSum):
for num1 in self.numbers:
for num2 in self.numbers:
if num1 + num2 == desiredSum and num1 != num2:
return True
return False
回答by TheLazyScripter
class TwoSum(object):
def __init__(self):
self.__data = []
def __repr__(self):
return repr(self.__data)
def add(self, n):
self.__data.append(n)
def find(self, n):
for i, v in enumerate(self.__data):
for x, v2 in enumerate(self.__data):
if i!= x and v + v2 == n:
return True
return False
回答by Tang
Here is my solution, just another reference for any potential people who may see this question. Basically, I combined all above answers to get this solution. Credits to @Keatinge, @mgilson, @TheLazyScripter. Thank you guys all.
这是我的解决方案,对于可能会看到这个问题的任何潜在人来说,这只是另一个参考。基本上,我结合了上述所有答案来获得此解决方案。感谢@Keatinge、@mgilson、@TheLazyScripter。谢谢大家。
class TwoSum(object):
def __init__(self):
self.added_items = set() # Make the `dict` -> `set` swap here too...
def add(self, n):
self.added_items.add(n)
def find(self, n):
for nums in itertools.combinations(self.added_items, 2):
if sum(nums) == n:
return True
return False
test = TwoSum()
test.add(1)
test.add(3)
test.add(5)
print(test.find(4))
print(test.find(7))
回答by mgilson
The dict
at the class level and the dict
in the method are different
所述dict
在类级和dict
在所述方法中是不同的
In the method, dict
is the builtin python type. If you want to modify the dict
on the class, you could try something like type(self).dict[n] = n
在方法中,dict
是内置的python类型。如果你想修改dict
类上的,你可以尝试像type(self).dict[n] = n
Also, for what it's worth, if your dict is always going to have the value == key, you might want to consider using a set
instead.
此外,对于它的价值,如果您的 dict 总是会有 value == 键,您可能需要考虑使用 aset
代替。
Finally, you'd probably be better off defining dict
as an instance attribute rather than a class attribute:
最后,您最好将其定义dict
为实例属性而不是类属性:
class TwoSum(object):
def __init__(self):
self.added_items = set() # Make the `dict` -> `set` swap here too...
def add(self, n):
self.added_items.add(n)