The most comprehensive usage of Python deduction

Preface

The text and pictures in this article are from the Internet and are for learning and communication purposes only. They do not have any commercial use. If you have any questions, please contact us for processing.

PS: If you need Python learning materials, you can click on the link below to get it yourself

Python free learning materials and group communication answers Click to join


1.Pythonic-very Pythonic

Write a piece of code to generate a list of squares of numbers between 1 and 100. The answer is:

1,4,9,16...

If you write like this, you won't be Pythonic:

nums = []
for i in range(1,101):
    nums.append(i*i)
print(nums)

The correct way of writing is to use Python's deduction:

nums = [i*i for i in range(1,101)]

2. Conditional derivation

Method to generate a list containing numbers between 1 and 100 that are multiples of 3:

9,36,81...

Code:

nums = [i*i for i in range(1,101) if i%3==0]

3. Conditional expression

Generate a list, if it is a multiple of 3, use the square, otherwise use the number itself:

1,2,9,4,5,36...

Code:

nums = [i*i if i%3==0 else i for i in range(1,101)]

Combining the three examples above, let's take a look at the deduced summary:

  • The deduction formula derives a list from an enumerable data (list, tuple, set, dictionary, etc.). It is also possible to derive generators, sets or dictionaries.
  • The derivation formula can add derivation conditions, and only derive the elements that meet the conditions
  • The elements to be derived are generated using expressions, and different elements can be generated with if else
[表达式 if 表达式条件 else 分支 for i in 序列 if 推导条件]

4. Use functions

What if the derivation conditions or expressions are particularly complicated? You can use functions.

Derive all prime numbers between 1-100: 2, 3, 5, 7...

def is_prime(num):
    if num == 1:
        return False  
    for i in range(2,num):
       if (num % i) == 0:
           return False
    else:
       return True

p_nums = [i for i in range(1,100) if is_prime(i)]
print(p_nums)

Putting the deduced condition in the function can not only deal with complex conditions, but also use the concise notation of deduction.

Similarly, if the process of generating the derivation result is complicated, you can also put the logic in the function.

Derive all the years between 1900 and 2021, mark leap years, and generate the result:

1900, 1901, 1902, 1903, '闰1904'

Code:

def is_run(year):
    if (year % 4) == 0:
       if (year % 100) == 0:
           if (year % 400) == 0:
               return True   # 整百年能被400整除的是闰年
           else:
               return False
       else:
           return True       # 非整百年能被4整除的为闰年
    else:
       return False 

ryears = [f'闰{y}' if is_run(y) else y for y in range(1900, 2021)]    
print(ryears)

5. Nested expressions-not recommended

From 2000 to 2021, generate each month: '2000: January', '2000: February', '2020: March', ..., '2021: December'

monthes = [f'{y}年:{m}月' for y in range(2000, 2022) for m in range(1,13) ]

There are two for loops, similar to:

monthes = []
for y in range(2000, 2022):
    for m in range(1,13):
        monthes.append(f'{y}年:{m}月')

6. Derive huge lists-don't do this!

Derive the square of the number between 1 and 10 billion, the code is as follows:

nums = [i*i for i in range(1,10000000000)]

But this code is likely to freeze your computer, unless your computer is a supercomputer. Because it has to do 10 billion calculations in memory, and then save these 10 billion numbers.

7. Use the generator

In this case, we should use a deduction generator, the usage is very simple:

  • Just change the square brackets to parentheses
nums = (i*i for i in range(1,10000000000))
print(nums)
print(next(nums))
print(next(nums))
print(next(nums))

Printed out is a generator:

<generator object <genexpr> at 0x7fa0b422feb0>
1
4
9

This is a generator. It will not generate 10 billion numbers at once. Only when next() is called will it generate a new one and return it to you. In other words, only one number is stored at the same time.

8. Derive a dictionary

The way to derive a dictionary is very similar to that of a list, except:

  • Use braces
  • Using key-value pairs to
    derive a dictionary consisting of numbers and number squares, the result is this:
{1: 1, 2: 4, 3: 9, ..., 100: 10000}

Code:

nums_dict = {n:n*n for n in range(1,101)}
print(nums_dict)

Conversely, the square is at the front and the number is at the back:

nums_dict = {n*n:n for n in range(1,101)}
print(nums_dict)

Sort the following dictionaries by score:

{'麦叔':59, '张三':87, 'FGA':78, '石石':100, '莫名':90}

Sort results:

{'石石': 100, '莫名': 90, '张三': 87, 'FGA': 78, '麦叔': 59}

Code:

scores = {'麦叔':59, '张三':87, 'FGA':78, '石石':100, '莫名':90}
sored_scores = {item[0]:item[1] for item in sorted(scores.items(), key=lambda item:item[1], reverse=True)}
print(sored_scores)

1. First turn the dictionary scores into a list of tuples: scores.items()
2. Use the sorted function to sort the list of tuples: sorted(scores.items(), key=lambda item:item[1], reverse=True )
3. The sorting process uses lambda to specify the second column of the tuple to be sorted: key=lambda item:item[1]. The default is the first column.
4. Specify the reverse order, that is, the higher score is in the front: reverse=True
5. Use the deduction to generate a sorted list of tuples to generate a new sorted dictionary: {item[0]:item [1] for item in ...}

9. Deriving Set

The way to derive a set is the same as a list, the difference is:

1. Use braces, similar to deriving a dictionary, but it is a single element, not a key-value pair.
2. The collection will automatically filter out duplicate elements.
The following list of names, after removing the leading and trailing spaces, remove the duplicate names:

[ '麦叔', '张三', ' 麦叔 ', 'FGA ', '张小三', 'FGA', '石石',' 莫名','莫名' ]

Derivation result:

{'石石', 'FGA', '张小三', '莫名', '张三', '麦叔'}

Code:

names = [ '麦叔', '张三', ' 麦叔 ', 'FGA ', '张小三', 'FGA', '石石',' 莫名','莫名' ]
new_names = {n.strip() for n in names}
print(new_names)

Guess you like

Origin blog.csdn.net/pythonxuexi123/article/details/112846507