Skip to content

Instantly share code, notes, and snippets.

Created Oct 15, 2021
What would you like to do?
filter the list of strings:
# example: add "weekend" to Saturdays and Sundays in October of each year
t = time.perf_counter()
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
strLoop = []
for d in datstrlist:
if (d.endswith("urday") or d.endswith("unday")) and "Oc" in d:
strLoop.append(d + " = Oct weekend")
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
tLoop = time.perf_counter() - t
print(f'{tLoop:.4f} sec')
t = time.perf_counter()
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
c = [d + " = Oct weekend" if ((d.endswith("urday") or d.endswith("unday")) and "Oc" in d) else d for d in datstrlist]
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
tComp = time.perf_counter() - t
print(f'{tComp:.4f} sec: comprehension vs loop: {100*(tComp/tLoop-1):.1f}%')
df = pd.DataFrame(list(zip(strLoop,c)), columns=("loop","comprehension"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment