リスト内包表記
リスト内の全ての要素を2倍にする
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] newlist = [n*2 for n in mylist] print(newlist)
[2, 4, 6, 8, 10, 12, 14, 16, 18]
リスト内の偶数のみ取り出す
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] newlist = [n for n in mylist if n%2==0] print(newlist)
[2, 4, 6, 8]
リスト内の偶数は”even”、奇数は”odd”とする
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] newlist = ["even" if n%2==0 else "odd" for n in mylist] print(newlist)
['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
辞書内包表記
辞書の要素を全て2倍にする
mydict = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5} newdict = {k:v*2 for k,v in mydict.items()} print(newdict)
{'a': 2, 'c': 6, 'b': 4, 'e': 10, 'd': 8}
辞書の要素が偶数であるもののみ取り出す
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] newdict = {k:v for k,v in mydict.items() if v%2==0 } print(newdict)
{'b': 2, 'd': 4}