LoginSignup
4
3

More than 5 years have passed since last update.

Python で iterator の次の値を取得しながら走査したい

Last updated at Posted at 2018-01-30

やりたいこと

Ruby での

(1...10).each_cons(2).to_a
#=> [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]

を Python でやりたい。

方法 1

import itertools

numbers = range(1, 10)
it1, it2 = itertools.tee(numbers)
next(it2)
list(zip(it1, it2))
# [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]

方法 2

list や range など subscriptable (添え字にアクセス可能) なオブジェクトならこの方法がシンプルでした。(@shiracamus さん、ありがとうございます :bow:)

numbers = range(1, 10)
list(zip(numbers, numbers[1:]))
# [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
4
3
4

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
3