問題是,list.remove
回報None
。雖然您可以easely解決這個問題通過更換list1=list1.remove(...)
,我可能會建議您其他的解決方案,
- 不修改列表1,列表2,因爲這可能會導致一個bug的代碼;
- 是快一點,因爲list.remove不是很有效
建議代碼:
import timeit
from itertools import izip_longest
def via_remove(l1, l2):
count = 1
while max(l1)>min(l2):
count+=1
l1.remove(max(l1))
l2.remove(min(l2))
return count
def with_itertools(l1, l2):
c = 1
for l1_max, l2_min in izip_longest(sorted(l1, reverse=True), sorted(l2)):
if l1_max <= l2_min:
break
c += 1
return c
print timeit.timeit('from __main__ import via_remove; via_remove(range(1000), range(1000))', number=100)
7.82893552113
print timeit.timeit('from __main__ import with_itertools; with_itertools(range(1000), range(1000))', number=100)
0.0196773612289