簡體   English   中英

Python - 確定集合中是否存在任何對象的優雅方法

[英]Python - Elegant method of determining whether any objects exist in a collection

我有以下 function - SomeFunction - 它接受事件集合作為參數,即 IncidentsIn。

然后我需要構建一個字符串 - RetStr - 取決於 IncidentsIn 中是否有任何詳細信息。

目前,如果存在詳細信息,我將向 k 添加 1,然后測試 k 的值以查看字符串是否更新為“未報告優先級”。 這不是使用 Python 優雅。 有沒有更好的辦法?

def SomeFunction(IncidentsIn):

    RetStr = 'Incidents: '
    k = 0

    for z in (x for x in IncidentIn if x.Priority in ('1', '2', '3')):
        k += 1
        RetStr += 'Add incident detail to string'

    if k == 0:
        RetStr += 'No Priorities reported'

你可以先得到

 items = (x for x in ...)

然后使用 `len(items)

 if len(items): 
     RetStr += 'No Priorities reported'` 
 else:
     for z in items:
         RetStr += 'Add incident detail to string

或者您可以創建包含詳細信息的列表,然后檢查它是否不為空。

 items = (x for x in ...)

 details_str = []  # empty list

 for z in item:
     details_str.append( 'Add incident detail to string' )

 if details_str:
     RetStr = 'Incidents: ' + "".join(details_str)
 else:
     RetStr = 'Incidents: No Priorities reported'

當然你可以對空字符串做同樣的事情

 items = (x for x in ...)

 details_str = ""  # empty string

 for z in item:
     details_str += 'Add incident detail to string' )

 if details_str:
     RetStr = 'Incidents: ' + details_str
 else:
     RetStr = 'Incidents: No Priorities reported'

暫無
暫無

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

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