5 Powerful Python One-Liners You Should Know: 1-Typecasting of All Items in A List
5 Powerful Python One-Liners You Should Know: 1-Typecasting of All Items in A List
Know
1- Typecasting of all items in a list
This is useful when you need to change the type of values in a list.
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]
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
print(np.matrix(A))
print()
print(np.matrix(transpose_A))
Output:
[[1 2 3]
[4 5 6]
[7 8 9]]
[[1 4 7]
[2 5 8]
[3 6 9]]
Suppose that we have staff data storing in a dict and want to exchange
key-value pairs.
>>> staff = {'Data Scientist': 'John', 'Django Developer': 'Jane'}
We can use dictionary comprehension to swap key-value pairs.
>>> staff = {i:j for j, i in staff.items()}
Let’s print the result:
>>> print(staff)
Output:
{'John': 'Data Scientist', 'Jane': 'Django Developer'}
-------------------------------------------------------------------------------------------------------------------------------
Source: https://levelup.gitconnected.com/5-powerful-python-one-liners-you-should-know-469b9c4737c7