これ以上はサンプルコードや本での勉強が重要になってきます
辞書型の使い方
変数= {"文字1":値1,"文字2":値2,..."文字n":値n}
とすると、文字nに対応した値nを取得できます
さて今回のタスクは 「文字の置き換え」です
例えばABCと入力すると、それに対応された数字123が出力される、といった形です。
試しに"Python"という文字を"123456"に変換するコードを書いてみます
最初は愚直に書いてみます
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
moji = "Python" | |
mlist = list(moji) | |
for i in range (len(mlist)): | |
if moji[i] == "P": | |
print(1,end="") | |
elif moji[i] =="y": | |
print(2,end="") | |
elif moji[i] =="t": | |
print(3,end="") | |
elif moji[i] =="h": | |
print(4,end="") | |
elif moji[i] =="o": | |
print(5,end="") | |
elif moji[i] =="n": | |
print(6,end="") |
moji = "Python" #文字を指定
mlist = list(moji) #mojiを1文字ずつ区切り、mlistに格納
for i in range (len(mlist)): #iをmlistの要素数だけ繰り返す
if moji[i] == "P": #moji[i]の文字がPであれば
print(1,end="") #1を出力する 改行なし
以下
これをスマートに辞書型で書きます
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
a = {"P":1,"y":2,"t":3,"h":4,"o":5,"n":6} #辞書に対応した文字と数字を入れる | |
moji = "Python" #変換前の文字をmoji変数に入れる | |
mojiList = list(moji) #mojiを1文字ずつリストに入れる | |
for i in range (len(mojiList)): #mojiListの要素数だけ繰り返し | |
print (a[mojiList[i]], end="") #辞書型に対応した数字を出力, 改行なし |
いやいや、for文にはリストをそのまま入れられるんでしたね、lenはつい癖でいれちゃいます
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
a = {"P":1,"y":2,"t":3,"h":4,"o":5,"n":6} | |
moji = "Python" | |
mojiList = list(moji) | |
for i in mojiList: | |
print (a[i], end="") |
だいぶスッキリしました!
最初のforとifの力技では文字が増えるたびにどんどん行数が増えますが、辞書型を使えば辞書の文字をいれるだけで大丈夫です。
今回ブログの書き方も途中でいろいろ思いついて、説明方法がバラバラですみませんでした(直さない)
0 件のコメント:
コメントを投稿