LoginSignup
34

More than 5 years have passed since last update.

Pythonでのlist, for文関連の便利ワザ

Posted at

listの各要素に同じ操作をする - map

map.py
def add1(str):         #文字の最後に1の文字を付け加える関数
      return str+'1'

list_str = ['a', 'b', 'c']
map(add1, list_str)
Out[3]: ['a1', 'b1', 'c1']

なお次のように書いても同じことが出来ます。

map.py
map(lambda x : x+'1', list_str)

これでも同じ(リスト内包表記)

map.py
[x+'1' for x in list_str]

条件一致要素だけを抜き出す - filter

リストの中から文字数が3の要素だけを抜き出します。

filter.py
list_words = ['toy', 'cat', 'dog', 'girl', 'house', 'boy']
filter(lambda x : len(x)==3, list_words)
Out[7]: ['toy', 'cat', 'dog', 'boy']

これでも同じ(リスト内包表記)

map.py
[x for x in list_words if len(x)==3]

重複をなくしたリストとその扱い - set

set.py
list_words2 = ['toy', 'cat', 'dog', 'girl', 'house', 'boy', 'toy', 'toy', 'cat', 'dog']
list_words2_unique = set(list_words2)

リスト内の要素の重複をなくしたsetオブジェクトができる

list_words2_unique
Out[8]: set(['boy', 'toy', 'house', 'dog', 'cat', 'girl'])

setオブジェクトは"add"というメソッドで要素を追加する事ができるが、
重複する要素を追加しても変化はない
リストにとって新たな要素の場合にのみ変化が起こる

set.py
list_words2_unique.add('dog')
list_words2_unique

Out[16]:
{'boy', 'cat', 'dog', 'girl', 'house', 'toy'}
set.py
list_words2_unique.add('sheep')  #リスト内に無い要素を追加する
list_words2_unique

Out[17]:
{'boy', 'cat', 'dog', 'girl', 'house', 'sheep', 'toy'} #追加される

また、Unionを使うと別のリストとの和集合が取られる

set.py
list_words2_unique.union(['lion', 'cow', 'dog', 'cat'])

Out[18]:
{'boy', 'cat', 'cow', 'dog', 'girl', 'house', 'lion', 'sheep', 'toy'}

For文で連番を使いたい- enumerate

for文で自動で連番をふるための方法

enumerate.py
list_words = ['toy', 'cat', 'dog', 'girl', 'house', 'boy']

for i, word in enumerate(list_words): #iに連番が入り、wordにリストの要素が入る
    print (i, word)

Out[19]: 
       (0, 'toy')
       (1, 'cat')
       (2, 'dog')
       (3, 'girl')
       (4, 'house')
       (5, 'boy')

2つの要素でFor文 - zip

zip.py
list_words = ['toy', 'cat', 'dog', 'girl', 'house', 'boy']
list_number =[21, 3, 12, 5, 6, 19]

#numにlist_numberの要素が、wordにlist_wordsの要素が入る
for num, word in zip(list_number, list_words):  
    print (num, word)

Out[20]: 
    (21, 'toy')
    (3, 'cat')
    (12, 'dog')
    (5, 'girl')
    (6, 'house')
    (19, 'boy')

上記のenumerateをzipで(無理やり)書くとすると下記のようになりますね。

length = len(list_words)

for i, word in zip(range(length), list_words):
        print (i, word)

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
34