python - 如何在 Python 中获取列表中的最后一个非空项?

标签 python list generator

我今天才开始学习 Python。

我有一个列表:

[text:u'Oranges', text:u'Apples', empty:'', empty:'']

如何获取列表中的最后一个非空项?在这种情况下,“苹果”。

我在 Get first non-empty string from a list in python 中看到, 他们得到第一个非空值。不确定如何获得最后一个。

最佳答案

next(s for s in reversed(list_of_string) if s)

如果您真的有字典,请使用 reversed(dictionary.values()),但请记住,您对字典所做的任何操作都会改变它的顺序,而且它的顺序并不一致不同版本的 Python 之间的方式,即使对于给定的状态。

如果您希望键按插入顺序保存,请使用 OrderedDict

关于python - 如何在 Python 中获取列表中的最后一个非空项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6946578/

相关文章:

python - 如何选择最小数量来自 > 0 的列表?

c# - 将字符串列表转换为单个字符串

neural-network - Keras ImageDataGenerator 慢

python StopIteration 与生成器和列表

python - 在 python 中替换它们之前存储定界符和定界符位置

python - gcloud 与 pip install 相关的问题

python - 如何使用 pytest 确认引发正确的异常

python - Celery 任务中的 Pyramid/SQLAlchemy 模型绑定(bind)

c# - 为什么 List<T>.IndexOf(T) 不返回可为空的 int 是否有实际原因?

python - Python 中 Eratosthenes 的惰性筛选