1

好的,在 Python 中我有列表:

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

现在,我只想将列表花的最后一个对象分配给一个名为毒的新列表。

我试过了:

poisonous=flowers[-1]

但是,此语句使有毒的字符串而不是列表。

4

4 回答 4

3
>>> 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']
于 2013-09-15T02:59:55.800 回答
2

试试这个

poisonous=flowers[-1:]

演示:

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

您的问题是,您正在索引,它返回一个对象。而切片将返回一个列表。

于 2013-09-15T02:55:07.810 回答
1

您可以将要分配的对象包装在方括号中以使其成为列表分配。

poisonous = [flowers[-1]]
于 2013-09-15T02:59:41.857 回答
0

而且,可能更有用:

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']
于 2013-09-15T04:27:42.323 回答