Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表索引必须是整数,而不是str 6_Python_Python 3.x_Record - Fatal编程技术网

Python 列表索引必须是整数,而不是str 6

Python 列表索引必须是整数,而不是str 6,python,python-3.x,record,Python,Python 3.x,Record,我对python非常陌生,我真的很难找到解决这个问题的方法 我只是不明白为什么我需要在我的列表中只包含整数,而我认为它们应该支持多种数据类型 我有一个非常简单的帐户注册字段输入系统,但我无法将项目添加到列表中 任何帮助都将不胜感激。我已经包括了我的代码和我收到的消息 useraccounts = {} group = [] forename = input('Forename: ') surname = input('Surname: ') DOB = input('DOB: ') stu

我对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
回溯(最近一次呼叫最后一次):
文件“/Users/admin/Documents/homography/Computing/testing/testing.py”,第11行,在
组['forename']=名
TypeError:列表索引必须是整数,而不是str

组是一个列表,它不能采用字符串索引。看起来您想改用字典:

useraccounts = []
group = {}

group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class

useraccounts.append(group)
请注意,您可能希望
useraccounts
成为此处的列表;您的代码试图在
对象上调用
.append()

或者将键和值直接内联到字典定义中:

useraccounts.append({
    'forename': forename,
    'surname': surname,
    'dob']: DOB,
    'class': stu_class})

您需要的是一本
词典

group = {}

group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
在原始代码中,
useraccounts
保留一个空的
dict
,您只需将其附加到列表中即可。如果您想将
添加到
用户帐户

useraccounts['key'] = group

看起来您希望
group
成为
dict
useraccounts
成为
列表。您可以将它们向后放置,以及附加:

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

useraccounts=[]#现在
group.append()
将失败。这太好了。谢谢你的快速回复,太好了。非常感谢您的快速响应。guys
useraccounts
是一个字典,因此它没有附加方法。我有一种感觉,OP认为
group.append(useraccounts)
会将
group
添加到
useraccounts
对我来说很好,我们其他人也需要rep@MartijnPieters;)