慣れているだけかもしれないが、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"]