Python list comprehension and dictionary comprehension are convenient, aren't they? For statements that tend to be redundant
List comprehension
>>> [i * 2 for i in range(10)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Dictionary comprehension
>>> {i: i * 2 for i in range(10)}
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
It is one shot.
I knew that list comprehensions could be realized using map and filter when trying to realize it with JavaScript, but since I was able to know how to write dictionary comprehensions, I will leave a memorandum.
If you check the list comprehension before the dictionary comprehension, in the above example,
[...Array(10).keys()].map((d) => {return d * 2});
Can be processed with Python
>>> [i * 2 for i in range(10) if i % 2 == 0]
[0, 4, 8, 12, 16]
Something that contains an if statement, such as, is redundant, but
[...Array(10).keys()].filter((d) => d % 2).map((d) => d * 2);
It can be written as.
It is a favorite dictionary comprehension, but in the above Python example
[...Array(10).keys()].reduce((obj, x) => Object.assign(obj, { [x]: x * 2 }), {})
It can be written as. To generalize
array.reduce((obj, x) => Object.assign(obj, { [key_maker(x)]: value_maker(x) }), {})
It becomes. It's a lot more verbose than Python, but I think it's still more concise than using a for statement.
Recommended Posts