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.

RubyistのためのPython配列操作対応表

Posted at

慣れているだけかもしれないが、Rubyは配列の操作の可読性が高く覚えやすかったが、

Pythonは触るたびに調べ直すことが多かったので、備忘録を残しておく

Ruby、Python共に、同じ操作でも色々な方法があるため一例になります

基本的な操作

arr = []
arr << 1
# arr => [1]

arr += [2, 3]
# arr => [1, 2, 3]
arr = []
arr.append(1)
# arr => [1]

arr.extend([2, 3])
# arr => [1, 2, 3]

複雑な操作

class Parent:
    def __init__(self, children):
        self.children = children
        
class Child:
    def __init__(self, name):
        self.name = name

parents = [
    Parent([Child("a"), Child("b")]),
    Parent([Child("c")])
]

[child.name for parent in parents for child in parent.children]
# => ["a", "b", "c"]

map

class Obj
  attr_accessor :a

  def initialize(a)
    @a = a
  end
end

arr = [Obj.new("a"), Obj.new("b"]
arr.map(&:a)
# => ["a", "b"]
class Obj:
    def __init__(self, a):
        self.a = a

arr = [Obj("a"), Obj("b")]

# リスト内包記述
[obj.a for obj in arr]
# => ["a", "b"]

# ラムダ式
list(map(lambda x: x.a, arr))
# => ["a", "b"]
0
0
0

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?