知っておきたいPythonの強力な5つのOne-Liners
という記事。
1- Typecasting of all items in a list
code:sample.py
# Example 1:
# Output:
# Example 2:
This is also useful when we want to make a list consisting of heterogonous items homogeneous.
# Output:
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:
>> print(flattened_list)
# Output:
4- Transpose of a Matrix
code:sample.py
# Example:
# Output:
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'}