LoginSignup
1
1

More than 5 years have passed since last update.

python3: given strをlist slicingで切ってdictionaryに投げ込む, dictionary comprehension

Last updated at Posted at 2016-03-03

例えば以下の様な文章があったとする。毎回読む度に元気をくれるアホな話なのでこいつを選んでみました(笑)

My friend ripped open a handwarmer, and when the powder got on his hands his parents told him his hands would disintegrate by age 30. We looked up what disintegrate meant later that night, and he bawled hysterically while staring at his hands.

「この文章をスペースごとに区切ってdictionaryに入れたい」なんてことがこの先あるかもしれません。いや、ないかもしれません。今回はそのやり方についてたまたまSOFで見つけたので勉強のメモがてら使ってみたいと思います。こちらの都合上、関数にまとめてから使うことにします。

s2 = s2 = "My friend ripped open a handwarmer, and when the powder got on his hands his parents told him his hands would disintegrate by age 30. We looked up what disintegrate meant later that night, and he bawled hysterically while staring at his hands"

def splitter(some_sentence):
    out = some_sentence.split() # split s by whitespace into out in a form of a list
    entries = dict([(x,y) for x,y in zip(out[::2], out[1::2])]) # loops through every word in a given sentence 1st word = key, 2nd word = value
    return entries
>>> splitter(s2)
{'that': 'night,', 'My': 'friend', 'a': 'handwarmer,', 'looked': 'up', 'told': 'him', 'what': 'disintegrate', 'and': 'he', 'by': 'age', 'bawled': 'hysterically', 'while': 'staring', 'got': 'on', '30.': 'We', 'the': 'powder', 'at': 'his', 'his': 'hands', 'would': 'disintegrate', 'meant': 'later', 'ripped': 'open'}

個人的にはリストスライシングの使い方に刺激を受けました。リストスライシングってどこにでも応用が効く素晴らしいメソッドだなと。
簡単に役割を説明すると

  1. まず適当に入れてきた文章をsplitでスペース毎にスライスしてoutに入れる。(リストで)['My', 'friend', 'ripped', 'open', 'a', 'handwarmer,', 'and', 'when', 'the', 'powder', 'got', 'on', 'his', 'hands', 'his', 'parents', 'told', 'him', 'his', 'hands', 'would', 'disintegrate', 'by', 'age', '30.', 'We', 'looked', 'up', 'what', 'disintegrate', 'meant', 'later', 'that', 'night,', 'and', 'he', 'bawled', 'hysterically', 'while', 'staring', 'at', 'his', 'hands']
  2. そのリストをout[::2]out[1::2]で分けて前者をx後者をyとする。言い方を変えればリストの中の一番最初から一個飛ばしで単語を選んでいく方がx。飛ばした単語を拾っていくのがyみたいなイメージ。
  3. zipxyをタプルの中に入れてペアにする。`[('My', 'friend'), ('ripped', 'open'), ('a', 'handwarmer,'), ('and', 'when'), ('the', 'powder'), ('got', 'on'), ('his', 'hands'), ('his', 'parents'), ('told', 'him'), ('his', 'hands'), ('would', 'disintegrate'), ('by', 'age'), ('30.', 'We'), ('looked', 'up'), ('what', 'disintegrate'), ('meant', 'later'), ('that', 'night,'), ('and', 'he'), ('bawled', 'hysterically'), ('while', 'staring'), ('at', 'his')]
  4. xkeyに。yvalueに入れてdict()でペアをくっつけて完成。

サイト上の例を構造分解するとこんな感じ:

# s = '#one cat #two dogs #three birds'
# >>> splitter(s)
# out = ['#one', 'cat', '#two', 'dogs', '#three', 'birds']
# out[::2]
# ['#one', '#two', '#three']
# out[1::2]
# ['cat', 'dogs', 'birds']

しかしこんな使い方は絶対しないと思うのでdictionary comprehensionの中にifを入れて取捨選択してその単語のみを入れるとしたほうが明らかに賢いと思います。もしくはenumerator的な関数をつくってkeyを思いきって番号にするのも有りだと思います。それなら単語の数に応じてkeyの番号が出てくるのでデータの扱いなどで大活躍しそうです。参考までに。

def enumerate(s, start=0):
    return zip([i for i in range(start, (start + len(s)))], s)
1
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
1
1