列表中的子列表

Rob*_*ntz 8 python list sublist

创建了一个列表 flowers

>>> flowers = ['rose','bougainvillea','yucca','marigold','daylilly','lilly of the valley']
Run Code Online (Sandbox Code Playgroud)

然后,

我必须分配列表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']
Run Code Online (Sandbox Code Playgroud)

如何保持列表花的前3个对象,同时保持列表中列表的外观?

Ash*_*ary 15

切片表示法[: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']
Run Code Online (Sandbox Code Playgroud)


Jon*_*nts 6

在Python中:

thorny = flowers[1-3]
Run Code Online (Sandbox Code Playgroud)

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

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

阅读有关Python切片的内容


Sau*_*ahu 5

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

e1  e2  e3  e4  e5  e6  e7  e8  e9  e10     << list elements
|<--FirstFew-->|        |<--LastFew-->|
        |<--MiddleElements-->|
Run Code Online (Sandbox Code Playgroud)
  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]
    
    Run Code Online (Sandbox Code Playgroud)
  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]
    
    Run Code Online (Sandbox Code Playgroud)
  3. 中间元素可以用正索引和负索引来表示。

    Above examples [2:5] and [-5:-2] covers this category.
    
    Run Code Online (Sandbox Code Playgroud)

仅列出花的前 3 个对象

[0 : 3]   //zero as there is nothing to exclude.
or
[:3]
Run Code Online (Sandbox Code Playgroud)