Created
February 22, 2016 15:56
-
-
Save drobati/00ffe2500550a0a0bf31 to your computer and use it in GitHub Desktop.
Return list until match is found
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
list(gen) | |
# ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] | |
items = list() | |
try: | |
while gen: | |
item = next(gen) | |
items.append(item) | |
if item == '4': break | |
except StopIteration: | |
print "log a message" | |
pass |
>>> print list(takewhile(lambda x: x != '4', ['0', '1', '2', '3', '4', '5']))
['0', '1', '2', '3']
Based on https://bpaste.net/show/e35bbcd193a7 via BlaXpirit
items = []
for item in gen:
items.append(item)
if item == '4': break
else:
print "Match was not found."
$ python -m cProfile test_append.py
8 function calls in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 test_append.py:1(<module>)
1 0.000 0.000 0.000 0.000 test_append.py:3(main)
5 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Where test_append.py is
1 gen = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
1
2 def main():
3 items = []
4 for item in gen:
5 items.append(item)
6 if item == '4':
7 return items
8 else:
9 print 'Match was not found'
10
11 if __name__ == "__main__":
12 main()
$ python -m cProfile test_slice.py
3 function calls in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 test_slice.py:1(<module>)
1 0.000 0.000 0.000 0.000 test_slice.py:3(main)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Where test_slice is
1 gen = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
2
1 def main():
2 for i, item in enumerate(gen):
3 if item == '4':
4 return gen[0:i + 1]
5
6 if __name__ == "__main__":
7 main()
Take it as you will.
Thanks @GrappigPanda
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there a more efficient means of producing
['0', '1', '2', '3', '4']
?