Pythonでの導出式(python 3)


リスト導出式
>>> li = [1,2,3,4,5,6]

#       
>>> li_a = [x**2 for x in li ]
>>> li_a
[1, 4, 9, 16, 25, 36]

#      
>>> li_b = [x for x in li if x%2==0]
>>> li_b
[2, 4, 6]

#             
>>> li_c = [[1,2], [3], [], [4,5,6]]
>>> li_d = [j for i in li_c for j in i ]
>>> li_d
[1, 2, 3, 4, 5, 6]

#   map
>>> li_1 = ['a', 'b', 'c', 'd']
>>> li_2 = [10, 20, 30, 40]
>>> li_e = list(map(lambda x, y:{x:y}, li_1, li_2))
>>> li_e
[{'a': 10}, {'b': 20}, {'c': 30}, {'d': 40}]

ディクショナリガイド
#     
>>> li = ['a', 'b', 'c', 'd', 'e']
>>> li_1 = {k:v for k, v in enumerate(li)}
>>> li_1
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}

#     
>>> dict_a = {'a':10, 'b':20, 'c':30}
>>> dict_b = {v:k for k, v in dict_a.items()}
>>> dict_b
{10: 'a', 20: 'b', 30: 'c'}