返回较大列表中每个第 n 个项目的列表的 Pythonic 方法 [英] Pythonic way to return list of every nth item in a larger list

查看:27
本文介绍了返回较大列表中每个第 n 个项目的列表的 Pythonic 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个从 0 到 1000 的数字列表.是否有一种pythonic/有效的方法来生成第一个和每个后续第 10 个项目的列表,即 [0, 10, 20, 30, ... ]?

Say we have a list of numbers from 0 to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item, i.e. [0, 10, 20, 30, ... ]?

是的,我可以使用 for 循环来做到这一点,但我想知道是否有一种更简洁的方法来做到这一点,甚至在一行中?

Yes, I can do this using a for loop, but I'm wondering if there is a neater way to do this, perhaps even in one line?

推荐答案

>>> lst = list(range(165))
>>> lst[0::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]

请注意,这比循环和检查每个元素的模数快约 100 倍:

Note that this is around 100 times faster than looping and checking a modulus for each element:

$ python -m timeit -s "lst = list(range(1000))" "lst1 = [x for x in lst if x % 10 == 0]"
1000 loops, best of 3: 525 usec per loop
$ python -m timeit -s "lst = list(range(1000))" "lst1 = lst[0::10]"
100000 loops, best of 3: 4.02 usec per loop

这篇关于返回较大列表中每个第 n 个项目的列表的 Pythonic 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆