我是python的新手,我真的很难找到解决这个问题的方法。
我只是不明白为什么我需要在列表中只包含整数,因为它们应该支持多种数据类型。
我有一个非常简单的帐户注册字段输入系统,我只是无法将这些项目添加到列表中。
非常感谢任何帮助。我已经包含了我的代码和收到的消息。
useraccounts = {}
group = []
forename = input('Forename: ')
surname = input('Surname: ')
DOB = input('DOB: ')
stu_class = input('Class: ')
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
group.append(user accounts)
这是错误消息:
Traceback (most recent call last):
File "/Users/admin/Documents/Homework/Computing/testing/testing.py", line 11, in <module>
group['forename'] = forename
TypeError: list indices must be integers, not str
答案 0 :(得分:1)
你想要的是dictionary
:
group = {}
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
在原始代码中useraccounts
保留一个空的dict
,您只需将其添加到列表中即可。如果您想将group
添加到useraccounts
:
useraccounts['key'] = group
答案 1 :(得分:1)
您希望group
成为dict
,useraccounts
成为list
。你有他们倒退,以及追加:
useraccounts = [] # <-- list
group = {} # <-- dict
forename = input('Forename: ')
surname = input('Surname: ')
DOB = input('DOB: ')
stu_class = input('Class: ')
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
useraccounts.append(group) # <-- reversed. this will append group to useraccounts
如上所述,您试图将useraccuonts
(空列表)附加到group
,dict
没有append
方法
答案 2 :(得分:0)
group
是一个列表,它不能采用字符串索引。看起来你想要使用字典:
useraccounts = []
group = {}
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
useraccounts.append(group)
请注意,您可能希望useraccounts
成为此处的列表;您的代码尝试在.append()
对象上调用group
..
或将键和值直接内联到字典定义中:
useraccounts.append({
'forename': forename,
'surname': surname,
'dob']: DOB,
'class': stu_class})