【发布时间】:2017-05-17 01:50:10
【问题描述】:
我创建了一个列表,并想从列表中选择一些要打印的项目。下面,我只想在索引 0 处打印“熊”,在索引 3 处打印“袋鼠”。我的语法不正确:
>>> animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
>>> print (animals[0,3])
Traceback(最近一次调用最后一次):文件“”,第 1 行,in print (animals[0,3]) TypeError: 列表索引必须是整数 或切片,而不是元组
我尝试在索引之间使用空格,但仍然报错:
>>> print (animals[0, 3])
Traceback(最近一次调用最后一次):文件“”,第 1 行,in print (animals[0, 3]) TypeError: list indices must be 整数或切片,而不是元组
我可以打印单个值或 0-3 的范围,例如:
>>> print (animals [1:4])
['python', 'peacock', 'kangaroo']
如何打印多个不连续的列表元素?
【问题讨论】:
-
不知道为什么你被否决了。对我来说似乎是一个合法的问题。
标签: python list python-3.x