I created a dictionary and I need to add the value of the single tuple into a new dictionary.I cannot seem to get my keys method to work. I get this error "TypeError: 'int' object is not subscriptable"
我创建了一个字典,我需要将单个元组的值添加到一个新的字典中。我似乎无法让我的密钥方法工作。我收到此错误“TypeError:'int'对象不可订阅”
This is where my key method is located. I get an error in the line that has newlist.append(i[0]). I am trying to append the key part of the tuple into a > new list name newlist
这是我的密钥方法所在的位置。我在newlist.append(i [0])的行中出错。我试图将元组的关键部分附加到>新列表名称新列表中
def keys(self):
newlist = self.flattened()
keylist = []
for i in newlist:
newlist.append(i[0])
return newlist
This is my TestCase for the keys method
这是我的TestCase的keys方法
class test_keys(unittest.TestCase):
def test(self):
s = Dictionary([[0, "zero"], [1, "one"], [2, "two"], [3, "three"]
self.assertEqual(s.keys(), [0, 1, 2, 3])
1 个解决方案
#1
0
The problem is that you are iterating through a list, and changing it simultaneously.
问题是您正在遍历列表并同时更改它。
Change
def keys(self):
newlist = self.flattened()
keylist = []
for i in newlist:
newlist.append(i[0])
return newlist
for
def keys(self):
newlist = self.flattened()
keylist = []
for i in newlist:
keylist.append(i[0])
return keylist
#1
0
The problem is that you are iterating through a list, and changing it simultaneously.
问题是您正在遍历列表并同时更改它。
Change
def keys(self):
newlist = self.flattened()
keylist = []
for i in newlist:
newlist.append(i[0])
return newlist
for
def keys(self):
newlist = self.flattened()
keylist = []
for i in newlist:
keylist.append(i[0])
return keylist