PyQはじめましたしめさばです。
オンラインPython学習サービス「PyQ™(パイキュー)」
さくさくっと進むのは良いのですが、進む分だけ忘れるので、メモを残そうかと思います。
リスト[]の操作
[box class=”blue_box” ]
- リストの末尾に要素を追加: リスト.append(要素)
- リストのインデックスの位置に要素を追加: リスト.insert(要素)
- リストの既存の要素の値変更: リスト[インデックス] = 変更したい値
- リストの末尾の要素の削除: リスト.pop()
- リストのインデックス位置の要素の削除: リスト.pop(インデックス)
[/box]
# 追加(末尾) |
print(‘++ 末尾に「山田」を追加 ++’) |
duty.append(‘山田’) |
|
# 追加(3番目) |
print(‘++ 前から3番目に「中村」を追加 ++’) |
duty.insert(2, ‘中村’) |
|
# 変更(2番目) |
print(‘++ 前から2番目を「西川」に変更 ++’) |
duty[1] = ‘西川’ |
|
# 削除(1番目) |
print(‘++ 前から1番目の社員を削除 ++’) |
duty.pop(0) |
|
# 最終状態を表示 |
for employee in duty: |
print(employee) |
fruit_line = [‘バナナ’, ‘りんご’] |
|
# 「みかん」を列の最後に置きました。 |
fruit_line.append(‘みかん’) |
|
# 前から2番目に「ぶどう」を置きました。 |
fruit_line.insert(1, ‘ぶどう’) |
|
# 前から4番目の果物を田中くんにあげました。 |
fruit_line.pop(3) |
|
# 前から2番目に「メロン」を置きました。 |
fruit_line.insert(1, ‘メロン’) |
|
# 一番後ろの果物を食べました。 |
fruit_line.pop() |
|
# 「パパイヤ」を列の最後に置きました。 |
fruit_line.append(‘パパイヤ’) |
|
# 先頭の果物を取り出して、末尾に移動しました。 |
last_fruit = fruit_line.pop(0) |
fruit_line.append(last_fruit) |
|
# 表示してみましょう(for文を利用し、一要素ずつ表示) |
for fruit in fruit_line: |
print(fruit) |
辞書{}(要素の追加)
health_result = {} |
|
health_result[‘名前’] = ‘佐藤’ |
health_result[‘年齢’] = 35 |
health_result[‘体重’] = 60 |
health_result[‘身長’] = 170 |
# 在庫項目の追加 |
stationery[‘消しゴム’] = 10 |
|
# 在庫の変更 |
stationery[‘えんぴつ’] = 20 |
|
# 在庫項目の削除 |
del stationery[‘のり’] |
|
# 表示 |
print(stationery) |
ファイルの読み込み
with open(‘input/lunch.csv’, encoding=’utf-8′) as f: |
for row in f: |
columns = row.rstrip().split(‘,’) |
name = columns[0] |
lunch = columns[1] |
|
if lunch == ‘コロッケ弁当’: |
print(name) |
output_rows = [] |
|
with open(‘./input/books.csv’, encoding=’utf-8′) as f: |
for row in f: |
columns = row.strip().split(‘,’) |
purpose = columns[2] # 会議室の利用目的 |
|
if purpose == ‘Python-勉強会’: |
output_rows.append(row) |
|
# ファイル’output/book_python.csv’へ書き込む |
with open(‘output/book_python.csv’, ‘w’, encoding=’utf-8′) as wf: |
for row in output_rows: |
wf.write(row) |
日付の扱い
str_date = ‘2016-10-20’ |
|
# 日付へ変換 |
base_date = datetime.strptime(str_date, ‘%Y-%m-%d’) |
# 5日前 |
before_5days = base_date – timedelta(days=5) |
# 文字列に変換 |
print_date = f'{before_5days:%Y-%m-%d}’ |
# 表示 |
str_date = ‘2016-10-20’ |
|
# 日付へ変換 |
base_date = datetime.strptime(str_date, ‘%Y-%m-%d’) |
# 5日前 |
before_5days = base_date – timedelta(days=5) |
# 文字列に変換 |
print_date = f'{before_5days:%Y-%m-%d}’ |
# 表示 |
print(print_date) |
ファイルを読み込んで日時に変換
with open(‘input/days.txt’, encoding=’utf-8′) as f: |
for row in f: |
day = datetime.strptime(row.rstrip(), ‘%Y-%m-%d’) # -か/かは、csvの内容に合わせる |
print(f'{day:%Y/%m/%d}’) |
会議室の予約数を集計するプログラム
book = {} |
|
# ファイルinput/room.csvを開いて、集計 |
with open(‘input/room.csv’, encoding=’utf-8′) as f: |
for row in f: |
columns = row.rstrip().split(‘,’) |
room = columns[0] |
|
if room in book: |
book[room] += 1 |
else: |
book[room] = 1 |
|
# 表示 |
print(book) |
まだまだ先は長いね(^_^;)
コメント