如何在 Python 中获取列表中的最后一个非空项?
我今天刚开始学习Python。
我有一个列表:
[text:u'Oranges', text:u'Apples', empty:'', empty:'']
如何获取列表中最后一个非空项目?在这种情况下,“苹果”。
我在 从列表中获取第一个非空字符串中看到在 python 中,它们获取第一个非空值。不知道如何获得最后一个。
I just started learning Python today.
I have a list:
[text:u'Oranges', text:u'Apples', empty:'', empty:'']
How do I get the last non-empty item in a list? In this case, 'Apples'.
I see in Get first non-empty string from a list in python, they get the first non-empty value. Not sure how to get the last.
如果您确实有一本字典,请使用
reversed(dictionary.values())
,但请记住,您对字典所做的任何操作都可能会更改它的排序,并且不同字典之间的排序方式不一致。即使对于给定的状态,Python 的版本也是如此。如果您希望键保持插入顺序,请使用
OrderedDict
。If you really have a dictionary, use
reversed(dictionary.values())
, but keep in mind that anything you do to the dictionary can change it's ordering, and it's not ordered in a consistent way between different versions of Python even for a given state.Use an
OrderedDict
if you want the keys kept in insertion order.