python3

python3 でリストを結合する方法

投稿日:2020年12月5日 更新日:

2つのリストを結合して、「リストのリストを作りたい場合」と、「1つの長いリストを作りたい」場合がある。


それぞれ、次のようにする。

# リスト2つを用意
l_1 = [1,2,3]
l_2 = [4,5,6]

l = [] # リストのリストを作る
l.append(l_1)
l.append(l_2)
print(str(l))

l = l_1 + l_2 # 結合リストを作る
print(str(l))

結果

[[1, 2, 3], [4, 5, 6]]
[1, 2, 3, 4, 5, 6]

-python3
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

pythonで配列(リスト)の、ある要素がわかっているときにその次の要素を取得する方法。

next() を使う。 例 my_arr = [‘春’,’夏’,’秋’,’冬’] my_iter = iter(my_arr) print(next(my_iter,’なし’)) print(next …

no image

python3 で、フォルダがなければ作成するプログラム

os.mkdir() 関数を使う。 すでにフォルダが存在している場合は、エラーを表示する。 例 import os folder_name = ‘./python_create_folder’ try …

no image

matplotlib でグラフ表示ウィンドウの画面上の位置を自由に設定する方法

matplotlib.use(‘TkAgg’) としておき、 get_current_fig_manager().window.wm_geometry(“+20+50”) として、(+20+50)のと …

no image

matplotlib でグラフの中に注釈の文字を書く方法

annotate を使う。 例 import numpy as np from matplotlib import pyplot as plt x = np.linspace(-10,10,100) …

no image

python3 でタプルを指定した要素で順に並び替える

タプルを、指定した要素で並び替えることができる。「key=lambda x 」で、引数 x を指定。lambda は無名関数を表す。 例 record = [(‘織田信長’, 1534, 15 …