列表中的子列表

时间:2012-11-02 00:34:39

标签: python list sublist

创建了一个列表flowers

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

然后,

我必须为列表thorny分配列表flowers的子列表,该列表由列表中的前三个对象组成。

这就是我的尝试:

>>> 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个对象,同时保持列表中列表的外观?

5 个答案:

答案 0 :(得分:14)

切片表示法是[: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']

答案 1 :(得分:6)

在Python中:

thorny = flowers[1-3]

这相当于flowers[-2],因为(1 - 3 == - 2),这意味着它从列表的末尾开始,即 - 从结尾开始的第二个元素 - 例如白天......

要切换到(但不包括)前3个元素,您可以使用thorny = flowers[:3],如果您想要在此之后的所有内容,那么它是flowers[3:]

阅读Python切片

答案 2 :(得分:2)

您需要flowers[0:3](或等效地flowers[:3])。如果您执行flowers[0-3](例如),则相当于flowers[-3](即flowers中的倒数第三项。)。

答案 3 :(得分:1)

你走了:

thorny = flowers[0:3]

答案 4 :(得分:0)

任何给定列表都可以有3种可能的子列表类型:

e1  e2  e3  e4  e5  e6  e7  e8  e9  e10     << list elements
|<--FirstFew-->|        |<--LastFew-->|
        |<--MiddleElements-->|
  1. FirstFew 主要由 + ve 索引提供。

    First 5 elements - [:5]      //Start index left out as the range excludes nothing.
    First 5 elements, exclude First 2 elements - [2:5]
    
  2. LastFew 主要由 -ve 索引提供。

    Last 5 elements - [-5:]       //End index left out as the range excludes nothing.
    Last 5 elements, exclude Last 2 elements - [-5:-2]
    
  3. MiddleElements 可以通过正面和负面索引呈现。

    Above examples [2:5] and [-5:-2] covers this category.
    
  4.   

    只是列表花的前3个对象

    [0 : 3]   //zero as there is nothing to exclude.
    or
    [:3]
    
相关问题