LoginSignup
2
4

More than 5 years have passed since last update.

Pythonでforをできるだけ書きたくないマンのためのスニペット

Last updated at Posted at 2018-08-16

はじめに

forをできるだけ書かずに縛りプレイやってみました。「読みにくい」とか「PEP8がー」とか知りません。
(※思いついたら随時更新します。)

同じ長さのリストで辞書を作る

list1 = ['a', 'b', 'c', 'd', 'e']
list2 = [1, 2, 3, 4, 5]
result = {}
for key, value in zip(list1, list2):
    result[key] = value

list1 = ['a', 'b', 'c', 'd', 'e']
list2 = [1, 2, 3, 4, 5]
result = dict(zip(list1, list2))


パースして辞書を作る

val1 = 'x=1;y=2;z=3'
val2 = 'a:5,b:1,c:8'
result = {}
for v in val1.split(';'):
    key, value = v.split('=')
    result[key] = value
for v in val2.split(','):
    key, value = v.split(':')
    result[key] = value

val1 = 'x=1;y=2;z=3'
val2 = 'a:5,b:1,c:8'
result = {
    **dict(map(lambda x: x.split('='), val1.split(';'))),
    **dict(map(lambda x: x.split(':'), val2.split(',')))
}


リストからn個ずつ要素を取り出してリストを作る

list1 = [1, 2, 3, 4, 5, 6]
n = 2
result = []
for i in range(0, len(list1), n):
    result.append(list1[i:i+n])

list1 = [1, 2, 3, 4, 5, 6]
n = 2
result = [*zip(*[iter(list1)]*n)]
2
4
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
2
4