list comprehension vs filter()vs set difference:过滤一个集合时,哪个效率最高?

问题描述 投票:-1回答:1

考虑到我有

  • 1个数组的整数转换为一个集合(命名为 neighbors)

  • 另外3个要避免的整数集(命名为 forbidden1, forbidden2forbidden3)

__

neighbors = {6, 12, 9}
forbidden1 = {1, 4, 7, 8}
forbidden2 = {2, 5, 0, 3}
forbidden3 = {6, 9}

__

以下哪种方案能最有效地过滤掉第一组中的禁止值?为什么?

A 列表理解 if 语句和逻辑运算符 and

[x for x in neighbors if x not in forbidden1 and x not in forbidden2 and x not in forbidden3]

B 列表理解 if 语句和联合运算符 |

[x for x in neighbors if x not in forbidden1 | forbidden2 | forbidden3]

C 用逻辑运算符过滤() and

filter(lambda x: x not in forbidden1 and x not in forbidden2 and x not in forbidden3, neighbors)

D 用联合运算符过滤()。|

filter(lambda x: x not in forbidden1 | forbidden2 | forbidden3, neighbors)

E 联合运算符的集差 |

neighbors.difference(forbidden1 | forbidden2 | forbidden3)
python filter set list-comprehension set-difference
1个回答
0
投票

试了一下(timeit python)。

A) 294 ns ± 28.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
B) 297 ns ± 26.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
C) 300 ns ± 31.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
D) 294 ns ± 19.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
E) 291 ns ± 21.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

所有的结果都差不多

© www.soinside.com 2019 - 2024. All rights reserved.