Here are some useful things to remember about Python's comprehensions.
nums = [1, 2, 3, 4, 5]
nums_double = [x * 2 for x in nums] #Double each element in the list nums
print(nums_double) # [2, 4, 6, 8, 10]
nums_even = [x for x in nums if x % 2 == 0]
print(nums_even) # [2, 4]
nums_2 = [[1, 2], [3, 4]]
nums_2_odd = [odd for nums in nums_2 for odd in nums]
print(nums_2_odd) # [1, 2, 3, 4]
nums_set = {1, 2, 3, 4, 5}
nums_set_square = {x**2 for x in nums_set}
print(nums_set_square) # {1, 4, 9, 16, 25}
nums_dict = {'one': 1, 'two': 2, 'three': 3}
nums_dict_rev = {value:key for key, value in nums_dict.items()}
print(nums_dict_rev) # {1: 'one', 2: 'two', 3: 'three'}
nums = [1, 2, 3, 4, 5]
nums_gen = (x for x in nums)
print(nums_gen) # generator object
for num in nums_gen:
print(num)
print("\n".join("Fizz"*(n%3== 0) + "Buzz"*(n%5== 0) or str(n) for n in range(1,101)))
Here is a summary of Python's comprehensions. If you think you can use it, try using it to shorten the code.
Recommended Posts