Skip to content

Instantly share code, notes, and snippets.

@mizushou
Last active July 29, 2019 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizushou/da96658abd21875be92d2caba951a957 to your computer and use it in GitHub Desktop.
Save mizushou/da96658abd21875be92d2caba951a957 to your computer and use it in GitHub Desktop.
list, dictionary comprehensionのサンプル
"""
dictionary-comprehension
"""
# Pythonはdictionary comprehensionもサポートしている
# syntax: <variable> = { key:new_value for (key, value) in <dictionary>.items() }
grades = {'Nora': 90, 'Lulu': 15, 'Gino': 60}
grades
# ---> {'Nora': 90, 'Lulu': 15, 'Gino': 60}
doubleGrades = { key: value*2 for (key, value) in grades.items() }
doubleGrades
# ---> {'Nora': 180, 'Lulu': 30, 'Gino': 120}
# もちろん、<condition>も追加することもできる
doubleGrades = { key: value*2 for (key, value) in grades.items() if value % 2 ==0 }
doubleGrades
"""
list-comprehension
"""
# Without list comprehension
list1 = []
for i in range(15):
if i % 2 ==0:
list1.append(i)
list1
# ---> [0, 2, 4, 6, 8, 10, 12, 14]
# With list comprehensions
# syntax: [<value_to_include> for <elem> in <sequence> if <condition>]
list2 = [i for i in range(15) if i % 2 == 0]
list2
# ---> [0, 2, 4, 6, 8, 10, 12, 14]
# <condition>はoptional
list3 = [i for i in range(15)]
list3
# ---> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment