Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

python - List.remove method not applicable as the function with the map builtin?

Question

Can List.remove not be used as the function to apply in the map(function, iterable, ...) builtin?

%%timeit
import random
m = _max = 10000
n = random.randint(1, m)

outer = random.sample(population=range(1, 2*n+1), k=2*n)
inner = random.sample(population=range(1, n+1), k=n)
print(f"outer is {outer}")
print(f"inner is {inner}")

# 622 ms ± 216 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# [o for o in outer if o not in inner]

# 347 ms ± 139 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
for i in inner:
    outer.remove(i)
print(outer)
---

outer is [16, 5, 9, 2, 8, 12, 1, 4, 7, 13, 14, 10, 3, 15, 6, 11]
inner is [4, 1, 5, 8, 6, 7, 2, 3]
[16, 9, 12, 13, 14, 10, 15, 11]

I thought it was applicable with the map but it returned a list of None. Please advise if it can be applied in some way, or the reason not applicable. Please point out if I made a mistake.

#%%timeit
import random
m = _max = 10000
n = random.randint(1, m)

outer = random.sample(population=range(1, 2*n+1), k=2*n)
inner = random.sample(population=range(1, n+1), k=n)
print(f"outer is {outer}")
print(f"inner is {inner}")

print(outer.remove)
print(list(map(outer.remove, inner)))
---

outer is [11, 3, 1, 5, 12, 9, 8, 4, 10, 6, 7, 2]
inner is [1, 3, 4, 6, 5, 2]
<built-in method remove of list object at 0x7f470b6fbd00>
[None, None, None, None, None, None]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It works as expected. remove affects the initial list but returns nothing (None). Print outer again and it should be shorter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...