Last active
September 4, 2016 08:34
-
-
Save zhyq0826/8081313 to your computer and use it in GitHub Desktop.
python 移除list 中的某个元素
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
import random | |
def slice_remove(s, item): | |
sorted(s) | |
start = s.index(item) | |
length = s.count(item) | |
a = s[0:start] | |
b = s[start+length:] | |
a.extend(b) | |
return a | |
def normal_remove(s, item): | |
while 1: | |
try: | |
s.remove(item) | |
except Exception, e: | |
break | |
return s | |
def random_test(): | |
s = [] | |
for i in range(0,1000000): | |
s.append(random.choice([0,1,2,3,4,5,6,7,8,9,10])) | |
return s | |
slice_remove(random_test(), 0) # [Finished in 2.5s] | |
# normal_remove(random_test(), 0) # [Finished in >900s] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment