由于某种原因,这不允许我在字典的键中添加字符串项。
这是我的代码:splitUserList(line)
的示例:
>>> splitUserList("1|24|M|technician|85711 ")
['1', 24, 'M', 'technician', '85711']
码:
def createUserList():
userList = []
totalUserList = []
f = open("u.user.txt")
for line in f:
userDict = {}
singleUserList = splitUserList(line)
userDict["age"] = singleUserList[1]
userDict["gender"] = singleUserList[2]
userDict["occupation"] = singleUserList[3]
singleUserList["zip"] = singleUserList[4]
userList.append(userDict)
return userList
为什么不起作用?
Traceback (most recent call last):
File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 20, in createUserList
TypeError: list indices must be integers, not str
最佳答案
我猜你的意思是
userDict["zip"] = singleUserList[4]
代替
singleUserList["zip"] = singleUserList[4] # <-- singleUserList is a list,
# and you cannot index it via a string