知っておきたいPythonの強力な5つのOne-Liners
という記事。
5 Powerful Python One-Liners You Should Know | by Görkem Arslan | Jul, 2021 | Level Up Coding
1- Typecasting of all items in a list
code:sample.py
# Example 1:
>> list(map(int, '1', '2', '3'))
# Output:
1, 2, 3
# Example 2:
This is also useful when we want to make a list consisting of heterogonous items homogeneous.
>> list(map(float, '1', 2, '3.0', 4.0, '5', 6))
# Output:
1.0, 2.0, 3.0, 4.0, 5.0, 6.0
2- Sum of digits of an integer
code:smaple.py
#You don’t have to use mathematical operators, i.e. / (division) and % (modulo) operators, to compute the sum of digits of an integer number. There is an alternative way to do that. If we convert the number to a string, everything becomes easy. But how? We’ve already known that strings are iterable so we can iterate over characters of a string with map() function. We’ll basically use this logic.
>> sum_of_digits = lambda x: sum(map(int, str(x)))
# Example:
>> print(sum_of_digits(1789))
# Output:
25
3- Flat a list that contains sublists
code:sample.py
# Example:
>> l = 1, 2, 3], 4, 5, 6, 7, 8, [9
>> flattened_list = item for sublist in l for item in sublist
>> print(flattened_list)
# Output:
1, 2, 3, 4, 5, 6, 7, 8, 9
4- Transpose of a Matrix
code:sample.py
# Example:
>> A = 1, 2, 3], 4, 5, 6, [7, 8, 9>>> transpose_A = list(i) for i in zip(*A)
# Output:
[1 2 3
4 5 6
7 8 9]
[1 4 7
2 5 8
3 6 9]
5- Swap keys and values in a dictionary
code:sample.py
>> staff = {'Data Scientist': 'John', 'Django Developer': 'Jane'}
>> staff = {i:j for j, i in staff.items()}
>> print(staff)
# Output:
{'John': 'Data Scientist', 'Jane': 'Django Developer'}