【问题标题】:How to take last element with a specific value in a list如何获取列表中具有特定值的最后一个元素
【发布时间】:2021-10-22 09:53:58
【问题描述】:

我有一个具有“类型”属性的 Document 对象。我需要循环一个 Document 列表,对于每个 document.type == "OTHER" 我必须取列表中的最后一个元素,它是一个 "MIC" document.type。我怎样才能轻松做到这一点?

【问题讨论】:

  • 你应该在你的问题中包括你的尝试以及什么对你不起作用。请参阅How to ask
  • 信息不足 - 添加文档和代码。

标签: python list sorting


【解决方案1】:

我已将列表颠倒并循环遍历它 如果新元素的类型不是某些类型之一,则将其视为其他类型并中断循环,因为它最初是该类型的最后一个

types = [float, str]

texts = ['hello', 3, 2.5, 'world', 7, 8, 1.4]

texts = texts[::-1]

for i in texts:
    ty = type(i)
    if ty in types:
        pass
    else:
        other = ty
        print(i)
        break

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 2022-11-15
    • 2023-03-29
    • 2021-09-12
    • 1970-01-01
    • 2016-07-22
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多