コンテンツにスキップ

04 元素記号

問題

“Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.”という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.

回答例

ここをクリックして回答を見る
s = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
keys = [1, 5, 6, 7, 8, 9, 15, 16, 19] # 1文字だけ取り出す位置を表す
words = s.split(" ")
result = {}
for i, word in enumerate(words, 1): # 単語の位置は1から数え始めたいので、第二引数に指定
if (i in keys):
result[i] = word[0] # 単語の位置が keys に一致する場合は、1文字だけ取り出す
else:
result[i] = word[0:2] # 単語の位置が key に一致しない場合は、スライスで2文字取り出す
print(result)