LoginSignup
0
1

More than 1 year has passed since last update.

Python(enumerate,zip,dict,os.path,directionary)

Last updated at Posted at 2021-09-10

今回は、enumerate,zip,dict,os.path,directionary について整理していく。

1. zipの基本

# zipでは複数のリストを同時に結び付けることができる。
list1=['東京','大阪','愛知','北海道','埼玉']#都道府県のリスト
list2=[1,2,3,4,5]#数値のリスト
for i, j in zip(list1,list2):
  print('{0}:{1}'.format(i, j))

>>>
東京:1
大阪:2
愛知:3
北海道:4
埼玉:5

2. enumerateの基本

# enumerateではインデックスとリストの中身を同時に紐つけることができる。
list1 = ['東京', '大阪', '愛知', '北海道', '埼玉'] # 都道府県のリスト
for i, j in enumerate(list1):
  print('{0}:{1}'.format(i, j))

>>>
0:東京
1:大阪
2:愛知
3:北海道
4:埼玉

3. zipとdictの組み合わせ

list1=['東京', '大阪', '愛知', '北海道', '埼玉'] # 都道府県のリスト
list2=[1, 2, 3, 4, 5] # 数値のリスト

# list1とlist2の中身について、zipで結びつけ、dictによってディレクショナリを作成する。
directionary = dict(zip(list1,list2))

print(directionary)
>>>{'東京': 1, '大阪': 2, '愛知': 3, '北海道': 4, '埼玉': 5}

4. directionary(keyとvalue)

directionary['三重'] = 6 # 要素の追加
print(directionary)

>>>
{'東京': 1, '大阪': 2, '愛知': 3, '北海道': 4, '埼玉': 5, '三重': 6}
# directionaryから要素の取得:itemsでは、keyとvalueを同時に取得することができる。
for ad_key,ad_val in directionary.items():
    print(ad_key,ad_val)

>>>
東京 1
大阪 2
愛知 3
北海道 4
埼玉 5

5. os.pathによるディレクトリ構造の作成

import os 
# データ数
num=5
# カレントディレクトリの取得
cur_directory = os.getcwd() 
#フォルダ名
folders = ["learn", "validation", "test"]
# フォルダごとのパス定義
for folder in folders:
  for i in range(num):
    print(os.path.join(cur_directory, folder, str(i) + ".py"))

>>>
/content/learn/0.py
/content/learn/1.py
/content/learn/2.py
/content/learn/3.py
/content/learn/4.py
/content/validation/0.py
/content/validation/1.py
/content/validation/2.py
/content/validation/3.py
/content/validation/4.py
/content/test/0.py
/content/test/1.py
/content/test/2.py
/content/test/3.py
/content/test/4.py
  • 上記のフォルダ構造の定義に基づき、mkdirをすることでディレクトリ構造の実態化をすることができる。 機械学習を行う前に、大量のデータを用意し、ディレクトリを用意して格納していく必要があるが、その際に自動化を図っておく技術があると便利。
0
1
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
0
1