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

python3 で辞書からランダムに要素を選択する方法

items() で辞書から要素を取り出し、random.choice でランダムに要素を選択する。 例 import random # 県庁所在地 mydict = {‘宮城県’:’仙台市’,’茨城県 …

no image

matplotlib でグラフの背景の色を変える方法(facecolor)

次のように、axes で facecolor を変更すればよい。 例 from matplotlib import pyplot as plt x = [2,7,8] y = [7,1 …

no image

matplotlib で、粗い刻みと細かい刻みの目盛りを表示する方法

set_major_locator で粗い刻みの目盛りを調整する。 set_minor_locator で、細かい刻みの目盛りを調整する。 以下の例で set_major_formatter は、表示 …

no image

python3 で、csv ファイルを読み込んで条件をみたす行の内容を表示する方法

csv.reader で読み込み、各行を読み込んで判定する。 例 import csv with open(‘data.csv’, ‘r’) as csv_file: reader = csv.rea …

no image

matplotlib で、x軸・y軸の目盛りを反対方向につけたい場合。

デフォルトでは、x軸はグラフの下に、y軸は左側につけられる。 例 import numpy as np from matplotlib import pyplot as plt x = np.lins …