python教程—len()在集合和列表方面的复杂性-Python实用宝典

# python教程—len()在集合和列表方面的复杂性

len()对于集合和列表的复杂度是O(1)。为什么处理集合需要更多的时间?

len()对于集合和列表的复杂度是O(1)。为什么处理集合需要更多的时间?

```~\$ python -m timeit "a=[1,2,3,4,5,6,7,8,9,10];len(a)"
10000000 loops, best of 3: 0.168 usec per loop
~\$ python -m timeit "a={1,2,3,4,5,6,7,8,9,10};len(a)"
1000000 loops, best of 3: 0.375 usec per loop
```

```\$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "len(a)"
10000000 loops, best of 3: 0.0369 usec per loop
\$ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "len(a)"
10000000 loops, best of 3: 0.0372 usec per loop
```

```for i in itertools.repeat(None, number):
len(a)
```

```\$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "\$(for i in {0..1000}; do echo "len(a)"; done)"
10000 loops, best of 3: 29.2 usec per loop
\$ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "\$(for i in {0..1000}; do echo "len(a)"; done)"
10000 loops, best of 3: 29.3 usec per loop
```

(结果仍然表明len()在列表和集合上具有相同的性能，但是现在您可以确定结果是正确的。)

<强>最后,< /强>

​Python实用宝典 (pythondict.com)