列表中的子列表

2024-06-06 17:28:43 发布

您现在位置:Python中文网/ 问答频道 /正文

创建了一个列表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个对象?


Tags: ofthe对象列表rosevalleyflowerslilly
3条回答

切片符号是[:3]而不是[0-3]

In [1]: flowers = ['rose','bougainvillea','yucca','marigold','daylilly','lilly of the valley']

In [2]: thorny=flowers[:3]

In [3]: thorny
Out[3]: ['rose', 'bougainvillea', 'yucca']

你需要做flowers[0:3](或者等价地说,flowers[:3])。如果你做了flowers[0-3](例如),它就相当于flowers[-3](即flowers中的第三个到最后一个项目)。

在Python中:

thorny = flowers[1-3]

这相当于flowers[-2],因为(1-3==-2),这意味着它从列表的末尾看,也就是说-末尾的第二个元素-例如daylly。。。

要分割到(但不包括)前3个元素,您可以使用thorny = flowers[:3],如果您想要这些元素之后的所有元素,那么它就是flowers[3:]

阅读Python切片

相关问题 更多 >