Pharmaceutical company researchers summarized Python's comprehensions

Introduction

Here are some useful things to remember about Python's comprehensions.

List comprehension

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)))

Summary

Here is a summary of Python's comprehensions. If you think you can use it, try using it to shorten the code.

Recommended Posts

Pharmaceutical company researchers summarized Python's comprehensions
Pharmaceutical company researchers summarized Python's data structures
Pharmaceutical company researchers summarized SciPy
Pharmaceutical company researchers summarized RDKit
Pharmaceutical company researchers summarized scikit-learn
Pharmaceutical company researchers summarized Pandas
Pharmaceutical company researchers summarized NumPy
Pharmaceutical company researchers summarized Matplotlib
Pharmaceutical company researchers summarized Seaborn
Pharmaceutical company researchers summarized Python control statements
Pharmaceutical company researchers summarized Python unit tests
Pharmaceutical company researchers summarized classes in Python
Pharmaceutical company researchers summarized functions in Python
Pharmaceutical company researchers summarized Python exception handling
Pharmaceutical company researchers summarized Python coding standards
Pharmaceutical company researchers summarized variables in Python
Pharmaceutical company researchers summarized regular expressions in Python
Pharmaceutical company researchers summarized web scraping using Python
Pharmaceutical company researchers summarized file scanning in Python
Pharmaceutical company researchers summarized database operations using Python
Pharmaceutical company researchers have summarized the operators used in Python
How to install Python for pharmaceutical company researchers
A pharmaceutical company researcher summarized the basic description rules of Python