Skip to content

Instantly share code, notes, and snippets.

@h3ik0th
Created Oct 15, 2021
Embed
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")
else:
strLoop.append(d)
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
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"))
df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment