![](/img/trans.png)
[英]Quickly determining using Python whether an image is (fuzzily) in a collection
[英]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.