1
2

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 3 years have passed since last update.

【Python】リスト 再利用しそうなコード

Last updated at Posted at 2020-08-04

リスト作成

空リスト

# 空リストを作成
empty = []      #  []
## 任意の値・要素数で初期化
n = [0] * 10              #  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# 2次元配列(リストのリスト)を初期化
n = [[0] * 4 for i in range(3)]   #  [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
【注】
data=[[list(range(1,9))]*3]*3 # この形式だと同じものを参照することになるので下記に
data=[[list(range(1,9)) for i in range(3)]for i in range(3)]

連番リスト

list(range(開始, 終了, 増分))

シャッフル

random.shuffle(リスト)

加工

抽出・切り出し

# スライス
# 最初は+1され。最後はそのまま
a = [1,2,3,4,5,6,7,8,9]
print(a[1:4])   # [2, 3, 4]

取出し

d=[2]
print(d[0])   # 2

a = [[1],[2]]
print(a[0][0])  # 1

追加

list.append(100)

list = list.append(row.split('-'))だとNG
'NoneType' object has no attribute 'append'

削除

list.remove(100)

結合

print([1, 2, 3] + [4, 5, 6])

操作

カウント

d=[0, 0, 5, 0, 3, 0, 6, 0, 0]
print(d.count(0))   # 6

差分

set(リスト[i][j])-set(data[i])

要素同士の掛け合わせ他

li1 = [1, 3, 5]
li2 = [2, 4, 6]

combine = [x * y for (x, y) in zip(li1, li2)]
#  [2, 12, 30]

コピー

1次元の場合、「list2=list1」とすると参照渡しのせいで、list2自体を書き換えてしまうとlist1も書き換えられるので、下記のように記述する。
2次元以上の場合は、このように記述できないのでdeepcopyを使う。

#  配列が1次元の場合
list2 = list1[:]
#  2次元以上の場合
import copy
list2 = copy.deepcopy(list1)

おまけ

# for-rangeの注意
for x in range(3):   =for x in [0,1,2]:
for x in range(1,3+1): =for x in [1,2,3]:

# 0/1入れ替え
a=abs(a-1)

# 別リストを元にソートする
ListA = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
ListB = [ 2,   1,   5,    0,   7,   3,   6,   4,   8]

Z = [x for y,x in sorted(zip(ListB,ListA))]
print(Z)  # ['d', 'b', 'a', 'f', 'h', 'c', 'g', 'e', 'i']

# フォルダリスト
import os

フォルダ="\\\\10.29.17.4\\RawData\\"

def フォルダリスト取得(フォルダ):
    path=フォルダ     # カレントディレクトリ内のファイル名
    files = os.listdir(path)
    files_dir = [f for f in files if os.path.isdir(os.path.join(path, f))]

    for i in files_dir:
        print(i)

フォルダリスト取得(フォルダ)

# ファイルリスト
import os

def ファイルリスト取得(フォルダ):
    ファイルリスト = os.listdir(フォルダ)     # カレントディレクトリ内のファイル名
    for i in ファイルリスト:
        item = i.split(".")
        if (item[1] == "CSV") & (i[:2]=="C0"):
            print(i)
        
ファイルリスト取得(フォルダ)

# サブフォルダ構造読み込み
import os

for folder, subfolders, files in os.walk(フォルダ):
    if subfolders==[]:
        print(folder)

# ファイルの有無判定
import os

if os.path.isfile(FileName)==False:
        return
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?