2017年4月10日 星期一

[ Python 常見問題 ] Pythonic way to return list of every n'th item in a larger list

Source From Here
Question
Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]. 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?

How-To
Below sample code use Python built-in range to create list:
>>> l = range(200)
>>> l.__class__

>>> l[0::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190]
>>> l[1::20]
[1, 21, 41, 61, 81, 101, 121, 141, 161, 181]


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...