文字列の結合方法
Pythonでは文字列結合に複数の方法が利用可能です。
プラス演算子による結合
greeting = "こんにちは"
name = "山田さん"
message = greeting + "、" + name
print(message) # 出力: こんにちは、山田さん
joinメソッドを使った効率的な結合
words = ["Python", "で", "文字列", "結合"]
sentence = "".join(words)
print(sentence) # 出力: Pythonで文字列結合
リスト操作の結合テクニック
拡張演算子を使用
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
combined = numbers1 + numbers2
print(combined) # [1, 2, 3, 4, 5, 6]
extendメソッドによる結合
list_a = [10, 20]
list_b = [30, 40]
list_a.extend(list_b)
print(list_a) # [10, 20, 30, 40]
NumPy配列の結合
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6]])
result = np.vstack((matrix1, matrix2))
print(result)
"""
[[1 2]
[3 4]
[5 6]]
"""
その他のデータ構造の結合
タプルの結合
tuple_x = (100, 200)
tuple_y = (300, 400)
merged = tuple_x + tuple_y
print(merged) # (100, 200, 300, 400)
辞書のマージ
dict1 = {'x': 1, 'y': 2}
dict2 = {'y': 3, 'z': 4}
combined_dict = {**dict1, **dict2}
print(combined_dict) # {'x': 1, 'y': 3, 'z': 4}