簡體   English   中英

僅將另一個列表的最后一個對象分配給新列表-Python

[英]Assigning to a new list just the last object of another list - Python

OK,在Python中,我有以下列表:

flowers = ["rose", "bougainvillea", "yucca", "marigold", "daylilly", "lilley of the valley"]

現在,我只想將列表花的最后一個對象分配給一個名為有毒的新列表。

我試過了:

poisonous=flowers[-1]

但是,此語句使有毒字符串而不是列表成為字符串。

>>> poisonous=[flowers[-1],] #take the last element and put it in a list
>>> poisonous
['lilley of the valley']
>>> poisonous=flowers[-1] #take the last element, which is a string
>>> poisonous
'lilley of the valley'
>>> poisonous=flowers[-1:] #take a slice of the original list. The slice is also a list.
>>> poisonous
['lilley of the valley']

試試這個

poisonous=flowers[-1:]

演示:

>>> flowers = ["rose", "bougainvillea", "yucca", "marigold", "daylilly", "lilley of the valley"]
>>> 
>>> flowers[-1:]
['lilley of the valley']

您的問題是,您正在建立索引,這將返回一個對象。 而切片將返回一個列表。

您可以將要分配的對象包裝在方括號中,以使其成為列表分配。

poisonous = [flowers[-1]]

而且,可能更有用:

flowers = [
    "rose", 
    "bougainvillea", 
    "poison oak",
    "yucca", 
    "marigold", 
    "daylily", 
    "lily of the valley",
]

snakes = [
    "king",
    "rattler",
]

poisonous = []

poisonous.append(flowers[-1])
poisonous.append(snakes[-1])

print poisonous

--output:--
['lily of the valley', 'rattler']

暫無
暫無

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

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