Last active
July 29, 2019 06:09
-
-
Save mizushou/da96658abd21875be92d2caba951a957 to your computer and use it in GitHub Desktop.
list, dictionary comprehensionのサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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