python - 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]
解决方案
It works as expected. remove
affects the initial list but returns nothing (None
). Print outer
again and it should be shorter.
推荐阅读
- tsql - 我有全名,只需要得到第一个和最后一个首字母
- javascript - React Hooks Idle Timeout for Functional Component
- android - API 29 媒体存储访问
- docker - Docker 网桥
- css - 如何垂直对齐输入字段文本和复选框?
- abap - 为什么`cl_gui_textedit->get_textstream`的结果是空的?
- python - next() 总是给出与 KFold 生成器相同的索引
- arrays - 如何从查询访问数据到 CGridView
- javascript - 当客户端连接到服务器时,NODE.JS 中的异步等待失败
- javascript - .ease(d3.easeLinear) 产生无法读取未定义的属性“indexOf”