python 报错list indices must be integers or slices,not str

Spring 2018-07-05 10:13:30
aliens = [];/*定义一个空的列
for alien_number in range(0,10):/
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien);
print(aliens);
for alien in aliens[0:3]:
# ~ print('..........')
# ~ print(aliens)
if aliens['color'] == 'green': /* list indices must be integers or slices,not str 这里报错了,我不知道怎么弄。哪位高人给看下
aliens['color'] = 'red'
aliens['points'] = 10
aliens['speed'] = 'fast'
print(aliens);
...全文
5569 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
WYHMingMing 2021-02-01
  • 打赏
  • 举报
回复
是这样的,aliens是一个列表,如果想要调用列表中的某一个元素,需要这样: 列表名[元素在列表中所在的下表] alien是一个字典,如果想要调用字典中的某一个键所对应的值,需要这样: 字典名[对应的键名] 例如: # coding:utf-8 # 英雄展示秀 heroes = ['钢铁大侠', '黑大寡妇', '雷大神', '灭大霸', '绿大巨人'] hero1 = {'name' : '钢铁侠', 'clothes' : '红色盔甲'} hero2 = {'name' : '蜘蛛侠', 'clothes' : '连体黑红格子秋衣秋裤'} hero3 = {'name' : '蝙蝠侠', 'clothes' : '黑色眼罩黑色披风'} hero4 = {'name' : '三门峡', 'clothes' : '发电站'} hero1234 = {'name' : '钢铁侠抱着蜘蛛侠骑着蝙蝠侠坐在了三门峡上', 'clothes' : '黑色眼罩红色盔甲黑红格子秋裤下面是发电站'} print('Heroes Show\n') # 输出英雄们 print('Heroes :\n') print(heroes[0]) print(heroes[1]) print(heroes[2]) print(heroes[3]) print(heroes[4]) # 详细输出英雄们 print('\nEach Hero :') print('\nHero1 :') print('Name : ' + hero1['name']) print('Clothes : ' + hero1['clothes']) print('\nHero2 :') print('Name : ' + hero2['name']) print('Clothes : ' + hero2['clothes']) print('\nHero3 :') print('Name : ' + hero3['name']) print('Clothes : ' + hero3['clothes']) print('\nHero4 :') print('Name : ' + hero4['name']) print('Clothes : ' + hero4['clothes']) print('\nHero1234 :') print('Name : ' + hero1234['name']) print('Clothes : ' + hero1234['clothes']) print('\nGoodbye! See you!') 运行结果:(输出端) Heroes Show Heroes : 钢铁大侠 黑大寡妇 雷大神 灭大霸 绿大巨人 Each Hero : Hero1 : Name : 钢铁侠 Clothes : 红色盔甲 Hero2 : Name : 蜘蛛侠 Clothes : 连体黑红格子秋衣秋裤 Hero3 : Name : 蝙蝠侠 Clothes : 黑色眼罩黑色披风 Hero4 : Name : 钢铁侠抱着蜘蛛侠骑着蝙蝠侠坐在了三门峡上 Clothes : 黑色眼罩红色盔甲黑红格子秋裤下面是发电站 Goodbye! See you! 能懂吗?望采纳,谢谢!
cyx200902 2021-01-23
  • 打赏
  • 举报
回复
引用 4 楼 weixin_51964556 的回复:
怎么没有看懂呢,所以到底是怎么改的
少了一个s
天上溪 2020-11-14
  • 打赏
  • 举报
回复
怎么没有看懂呢,所以到底是怎么改的
欢乐的小猪 2018-07-06
  • 打赏
  • 举报
回复
aliens是一个列表,里面有很多的alien
alien是一个字典,key包含color,points,speed
ghostgoodbye 2018-07-06
  • 打赏
  • 举报
回复
if aliens['color'] == 'green': /* list indices must be integers or slices,not str 这里报错了,我不知道怎么弄。哪位高人给看下
aliens['color'] = 'red'
aliens['points'] = 10
aliens['speed'] = 'fast'
print(aliens);
这里打错了,应该是alien
if alien['color'] == 'green':
alien['color'] = 'red'
alien['points'] = 10
alien['speed'] = 'fast'
print(alien);
Spring 2018-07-06
  • 打赏
  • 举报
回复
我再看看,谢谢了,真的感谢大家

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧