创建了一个列表flowers
>>> flowers = ['rose','bougainvillea','yucca','marigold','daylilly','lilly of the valley']
那么
我不得不给listthorny
分配listflowers
的子列表,它由列表中的前三个对象组成。
我就是这么想的:
>>> thorny = []
>>> thorny = flowers[1-3]
>>> thorny
'daylilly'
>>> thorny = flowers[0-2]
>>> thorny
'daylilly'
>>> flowers[0,1,2]
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
flowers[0,1,2]
TypeError: list indices must be integers, not tuple
>>> thorny = [flowers[0] + ' ,' + flowers[1] + ' ,' + flowers[2]]
>>> thorny
['rose ,bougainvillea ,yucca']
如何在保持列表内列表外观的同时,仅获取列表花的前3个对象?
切片符号是
[:3]
而不是[0-3]
:你需要做
flowers[0:3]
(或者等价地说,flowers[:3]
)。如果你做了flowers[0-3]
(例如),它就相当于flowers[-3]
(即flowers
中的第三个到最后一个项目)。在Python中:
这相当于
flowers[-2]
,因为(1-3==-2),这意味着它从列表的末尾看,也就是说-末尾的第二个元素-例如daylly。。。要分割到(但不包括)前3个元素,您可以使用
thorny = flowers[:3]
,如果您想要这些元素之后的所有元素,那么它就是flowers[3:]
。阅读Python切片
相关问题 更多 >
编程相关推荐