簡體   English   中英

列表中的子列表

[英]Sublist in a List

創建了一個列表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個對象,同時保持列表中列表的外觀?

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

在Python中:

thorny = flowers[1-3]

這相當於flowers[-2]因為(1 - 3 == - 2),這意味着它從列表的末尾看,即 - 從結尾的第二個元素 - 例如白天......

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

閱讀有關Python切片的內容

你會想做flowers[0:3] (或等同於flowers[:3] )。 如果你沒有flowers[0-3]例如),這將是相當於flowers[-3]即在第三到最后一個項目flowers )。

干得好:

thorny = flowers[0:3]

任何給定列表可以有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. 

只是列表花的前3個對象

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM