列表中的子列表

14

创建了一个名为flowers的列表

>>> flowers = ['rose','bougainvillea','yucca','marigold','daylilly','lilly of the valley']

接着,

我需要将列表flowers中前三个对象构成的子列表分配给列表thorny

这是我尝试的方法:

>>> 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']

如何仅获取列表flowers的前3个对象,同时保持列表内嵌列表的外观?


2
切片符号使用冒号而不是减号。 - Waleed Khan
5个回答

18

切片符号应该是 [: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']

8

使用Python:

thorny = flowers[1-3]

这相当于flowers[-2],因为(1 - 3 == -2),这意味着它从列表末尾开始查找,即倒数第二个元素,例如 daylilly...
要切片前三个元素(不包括第三个),可以使用thorny = flowers[:3],如果想取这些元素之后的所有内容,则使用flowers[3:]
请阅读有关Python切片的相关信息。

5
任何给定列表都可能有三种可能的子列表类型:
e1  e2  e3  e4  e5  e6  e7  e8  e9  e10     << list elements
|<--FirstFew-->|        |<--LastFew-->|
        |<--MiddleElements-->|
  1. FirstFew are mostly presented by +ve indexes.

    First 5 elements - [:5]      //Start index left out as the range excludes nothing.
    First 5 elements, exclude First 2 elements - [2:5]
    
  2. LastFew are mostly presented by -ve indexes.

    Last 5 elements - [-5:]       //End index left out as the range excludes nothing.
    Last 5 elements, exclude Last 2 elements - [-5:-2]
    
  3. MiddleElements can be presented by both positive and negative index.

    Above examples [2:5] and [-5:-2] covers this category.
    
只需列出花卉列表的前三个对象。
[0 : 3]   //zero as there is nothing to exclude.
or
[:3]

3
你需要使用 flowers[0:3] (或等效的,flowers[:3])来实现。如果你使用了 flowers[0-3](例如),那么它将相当于 flowers[-3](即 flowers 中倒数第三个项目)。

1
最后,有一个明确说明如何设置切片偏移量的答案! - gsamaras

1

请看这里:

thorny = flowers[0:3]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接