简体   繁体   English

Python - 确定集合中是否存在任何对象的优雅方法

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

I have the following function - SomeFunction - which accepts a collection of incidents as a parameter ie IncidentsIn.我有以下 function - SomeFunction - 它接受事件集合作为参数,即 IncidentsIn。

I then need to build a string - RetStr - depending on whether there are any details in IncidentsIn.然后我需要构建一个字符串 - RetStr - 取决于 IncidentsIn 中是否有任何详细信息。

At the moment I am adding 1 to k if details exist and then testing the value of k to see if the string is updated with 'No Priorities reported' or not.目前,如果存在详细信息,我将向 k 添加 1,然后测试 k 的值以查看字符串是否更新为“未报告优先级”。 This is not using Python elegance.这不是使用 Python 优雅。 Is there a better way?有没有更好的办法?

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'

You could first get你可以先得到

 items = (x for x in ...)

and next use `len(items)然后使用 `len(items)

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

Or you could create list with details and later check if it is not empty.或者您可以创建包含详细信息的列表,然后检查它是否不为空。

 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'

Of course you could do the same with empty string当然你可以对空字符串做同样的事情

 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