简体   繁体   中英

Sublist in a List

Created a list flowers

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

Then,

I had to assign to list thorny the sublist of list flowers consisting of the first three objects in the list.

This is what I tried:

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

How can I get just the first 3 objects of list flowers, while maintaining the look of a list inside a list?

Slicing notation is [:3] not [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']

In Python:

thorny = flowers[1-3]

This equates to flowers[-2] because (1 - 3 == -2), and that means it looks from the end of the list, ie - the 2nd element from the end - eg daylilly...

To slice up to (but not including) the first 3 elements, you can use thorny = flowers[:3] , and if you wanted everything after those, then it's flowers[3:] .

Have a read up on Python slicing

You'll want to do flowers[0:3] (or equivalently, flowers[:3] ). If you did flowers[0-3] (for instance) it would be equivalent to flowers[-3] (ie the third to last item in flowers .).

干得好:

thorny = flowers[0:3]

There can be 3 possible sublist types for any given list:

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. 

just the first 3 objects of list flowers

[0 : 3]   //zero as there is nothing to exclude.
or
[:3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM