0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[py2rb] zip

Last updated at Posted at 2022-03-02

はじめに

移植やってます。
( from python 3.7 to ruby 2.7 )

zip (Python)

import numpy as np

x = np.array([1, 2, 3])
y = np.array([4, 5, 6])

for a, b in zip(x, y):
    print(a, b)

# output
1 4
2 5
3 6

何の変哲もないように思われますが、pythonとnumpyの親密さが伺い知れます。

失敗(Ruby)

require 'numpy'

x = Numpy.array([1, 2, 3])
y = Numpy.array([4, 5, 6])

x.zip(y).each do |a, b|
  p [a, b]
end

# output
undefined method `zip' for array([1, 2, 3]):Numpy::NDArray (NoMethodError)

PyCall経由とはいえエラーになります。

成功(Ruby)

require 'numpy'

x = Numpy.array([1, 2, 3])
y = Numpy.array([4, 5, 6])

x.to_a.zip(y.to_a).each do |a, b|
  p [a, b]
end

to_aを使用して、一旦rubyの配列に変換する必要がありました。

成功(numpy.column_stack)

require 'numpy'

x = Numpy.array([1, 2, 3])
y = Numpy.array([4, 5, 6])

p Numpy.column_stack([x, y])

# output
array([[1, 4],
       [2, 5],       
       [3, 6]])

numpystack関数を使用して結合することも可能です。

おまけ(Numo-NArray)

numo-narray
require 'numo/narray'

x = Numo::NArray.cast([1, 2, 3])
y = Numo::NArray.cast([4, 5, 6])

x.to_a.zip(y.to_a).each do |a, b|
  p [a, b]
end

numo-narrayでも変換が必要の様です。

メモ

  • Python の zip を学習した
  • 百里を行く者は九十里を半ばとす
0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?