问题是,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