List comprehension, generator and dictionary comprehension in python

1. List generation

For a simple example, output an odd number between 1-20.

  • General practice
my_list = []
for i in range(21):
    if i % 2 == 1:
        my_list.append(i)

print(my_list)
# [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
  • List generation
print([i for i in range(21) if i % 2 == 1])
# [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

More complicated logic (square the odd numbers between 1-20 output)

def handel_item(item):
    return item * item

print([handel_item(i) for i in range(21) if i % 2 == 1])

# [1, 9, 25, 49, 81, 121, 169, 225, 289, 361]

2. Generator

First of all, the formula in the list [], replaced (), it becomes a generator.

my_list = (i for i in range(21) if i % 2 == 1)
print(type(my_list))
print(my_list)

# <class 'generator'>
# <generator object <genexpr> at 0x0000022BDABA64C8>

Each element can be output through a for loop

my_list = (i for i in range(21) if i % 2 == 1)
for i in my_list:
    print(i)

#1 3 5 7 9 11 13 15 17 19

Conversion between generators and list expressions

my_list = (i for i in range(21) if i % 2 == 1)

print(my_list)
new_list = list(my_list)
print(new_list)

# <generator object <genexpr> at 0x000002D5D63D64C8>
# [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

You can also yieldconstruct a generator and explain it later.

3. Dictionary deduction

Exchange key value order

my_dict = {
    
    "bobby1": 22, "bobby2": 23, "ming": 5}

reverse_dice = {
    
    value: key for key, value in my_dict.items()}

print(reverse_dice)
# {22: 'bobby1', 23: 'bobby2', 5: 'ming'}

Supplement: Set comprehension

my_set = {
    
    key for key,value in my_dict.items()}
print(my_set)
print(type(my_set))
# {'bobby1', 'bobby2', 'ming'}
# <class 'set'>

Although it can be used directly my_set = set(my_dict.keys()), it is not flexible and does not allow arbitrary logic to be added like a dictionary comprehension.

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106979641