I have the following function - SomeFunction
- which accepts a collection of incidents as a parameter ie IncidentsIn.
I then need to build a string - RetStr
- depending on whether there are any details in 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. This is not using Python elegance. 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)
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.