这段代码在 Python 里能怎么改写成效率更高的吗,听说 for 循环比较慢

2021-10-07 09:08:34 +08:00
 zxCoder
    xs = []
    ys = []
    zs = []
    for data in ls:
        _x, _y, _z = data
        xs.append(_x)
        ys.append(_y)
        zs.append(_z)
6444 次点击
所在节点    Python
33 条回复
niubee1
2021-10-07 13:35:14 +08:00
@NoAnyLove 我测了一下,zip 稍快一些
niubee1
2021-10-07 13:36:30 +08:00
niubee1
2021-10-07 13:37:15 +08:00
NoAnyLove
2021-10-07 13:41:01 +08:00
@niubee1 同意,你的版本更快,

In [101]: def t1(ls):
...: flat = list(itertools.chain.from_iterable(ls))
...: xs = flat[::3]
...: ys = flat[1::3]
...: zs = flat[2::3]
...: return xs, ys, zs
...:

In [102]: def t2(ls):
...: xs, ys, zs =list(zip(*ls))
...: return list(xs), list(ys), list(zs)

In [113]: ls=[[i, i+1, i+2] for i in range(1, 98, 3)]

In [114]: %timeit t1(ls)
4.26 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [115]: %timeit t2(ls)
3.2 µs ± 19.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
niubee1
2021-10-07 13:43:13 +08:00
其实省掉 extend 过程,直接返回数组的话,还能再提高点性能
niubee1
2021-10-07 13:45:12 +08:00
@NoAnyLove 🤝 其实大家思路都差不多,python 要提高效率的话,应该尽可能的使用内置函数
NoAnyLove
2021-10-07 13:57:43 +08:00
@niubee1 对,就是这个道理,内置函数底层执行更快 🤝
shyrock
2021-10-07 16:40:25 +08:00
@niubee1 #19 学习了。
wuwukai007
2021-10-08 11:13:56 +08:00
#19 楼 一行代码开启新世界
princelai
2021-10-08 18:14:49 +08:00
```python
def func4(ls):
xs = list(islice(chain.from_iterable(ls), 0, None, 3))
ys = list(islice(chain.from_iterable(ls), 1, None, 3))
zs = list(islice(chain.from_iterable(ls), 2, None, 3))


def func5(ls):
xs = list(compress(chain.from_iterable(ls), cycle([1, 0, 0])))
ys = list(compress(chain.from_iterable(ls), cycle([0, 1, 0])))
zs = list(compress(chain.from_iterable(ls), cycle([0, 0, 1])))
```
itertools 里的内置函数速度都还可以
rationa1cuzz
2021-10-09 09:39:44 +08:00
@niubee1 ls[::] 是干嘛?我怎么看不懂啊,求教,另外为什么我测的是列表推导式更快一点,数量级越大越明显
rationa1cuzz
2021-10-09 09:48:52 +08:00
@niubee1 另外,只有在 data=[(x,y,z),(x2,y2,z2,...)] 为元祖 zip 才会有明显速度优势,
data[(x,y,z),(x2,y2,z2,...)] range(100000)
for: spend_time:0.03163599967956543
列表推导式:spend_time:0.012620925903320312
zip: spend_time:0.0060007572174072266

data[(x,y,z),(x2,y2,z2,...)] range(100000)
for: spend_time:0.03195595741271973
列表推导式:spend_time:0.012039899826049805
zip: spend_time:0.016546964645385742
htaoreg
2021-10-10 11:38:52 +08:00
xs, ys, zs = zip(*ls)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/806172

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX