Python 如何将字符串附加到字典中的列表
我在尝试在字典中追加时遇到了一些麻烦,我真的不知道如何使用它,因为每次我尝试运行代码时,它都会说“'str'对象没有'append'属性”。。。我有这样的东西Python 如何将字符串附加到字典中的列表,python,string,list,dictionary,append,Python,String,List,Dictionary,Append,我在尝试在字典中追加时遇到了一些麻烦,我真的不知道如何使用它,因为每次我尝试运行代码时,它都会说“'str'对象没有'append'属性”。。。我有这样的东西 oscars= { 'Best movie': ['The shape of water','Lady Bird','Dunkirk'], 'Best actress':['Meryl Streep','Frances McDormand'], 'Best actor': ['Gary Oldman','Denzel Washington
oscars= {
'Best movie': ['The shape of water','Lady Bird','Dunkirk'],
'Best actress':['Meryl Streep','Frances McDormand'],
'Best actor': ['Gary Oldman','Denzel Washington']
}
所以我想做一个新的分类,然后我想做一个循环,在这个循环中,用户可以输入他想要的任何数量的被提名者
newcategory=input("Enter new category: ")
nominees=input("Enter a nominee: ")
oscars[newcategory]=nominees
addnewnominees= str(input("Do you want to enter more nominees: (yes/no):"))
while addnewnominees!= "No":
nominees=input("Enter new nominee: ")
oscars[newcategory].append(nominees)
addnewnominees= str(input("Do you want to enter more nominees: (yes/no):"))
有人知道如何在字典中使用append吗?不能在字符串中追加。首先形成一个列表,以便以后可以附加到该列表中:
oscars[newcategory] = [nominees]
不能附加到字符串。首先形成一个列表,以便以后可以附加到该列表中:
oscars[newcategory] = [nominees]
如前所述,如果将键的值创建为字符串,则不能在其上使用
append
,但如果将键的值设置为列表,则可以使用。以下是一种方法:
newcategory=input("Enter new category: ")
oscars[newcategory]=[]
addnewnominees = 'yes'
while addnewnominees.lower() != "no":
nominees=input("Enter new nominee: ")
oscars[newcategory].append(nominees)
addnewnominees = str(input("Do you want to enter more nominees: (yes/no):"))
如前所述,如果将键的值创建为字符串,则不能在其上使用
append
,但如果将键的值设置为列表,则可以使用。以下是一种方法:
newcategory=input("Enter new category: ")
oscars[newcategory]=[]
addnewnominees = 'yes'
while addnewnominees.lower() != "no":
nominees=input("Enter new nominee: ")
oscars[newcategory].append(nominees)
addnewnominees = str(input("Do you want to enter more nominees: (yes/no):"))
说明:
当输入作为stdin传递时,输入总是一个字符串
。因此,在第oscars[newcategory].append(提名者)
行,它抛出了一个错误,因为解释器不知道newcategory
是一个列表,所以首先我们需要将它定义为list by
oscars[newcategory]= list()
然后我们可以根据用户的需要添加被提名人
说明:
当输入作为stdin传递时,输入总是一个字符串
。因此,在第oscars[newcategory].append(提名者)
行,它抛出了一个错误,因为解释器不知道newcategory
是一个列表,所以首先我们需要将它定义为list by
oscars[newcategory]= list()
然后我们可以根据用户的需要添加被提名人 虽然从技术上讲它不是追加,但是可以通过
my_string+=“something to append”
@Julien获得相同的字符串“追加”结果,同意。但这称为字符串连接:)。字符串没有append方法,但列表有。虽然从技术上讲它不是append,但通过my_string+=“something to append”
@Julien,可以获得字符串上相同的“append”结果。但这称为字符串连接:)。字符串没有append方法,但列表有。