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

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

问题描述

说我们有一个从0到1000的数字列表.是否有一种pythonic/有效的方法来生成第一项和随后的第十项的列表,即[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个项目的列表的Python方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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