LoginSignup
4
4

More than 5 years have passed since last update.

Python と Ruby で配列 (リスト) から要素を n 個おきに取り出す

Last updated at Posted at 2017-04-23

はじめに

僕は普段は Ruby を書いているのですが、最近趣味で Python を触り始めました。Python のリストのスライスを知って便利だなと思いました。ところで、Python の array[::3] という書き方は Ruby でどう書けばいいだろうとふと疑問に思ったので書き比べてみました。

Python

n = 3
array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
array[::n] #=> [0, 3, 6, 9]

Ruby

n = 3
array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
array.select.with_index { |_, i| i % n == 0 } #=> [0, 3, 6, 9]

うーむ、もっといい書き方はないだろうか… :thinking:

4
4
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4