current position:Home>Python's five strange skills will bring you a sense of enrichment in mastering efficient programming skills

Python's five strange skills will bring you a sense of enrichment in mastering efficient programming skills

2022-02-01 05:41:20 Yunyun yyds

The following five are about Python Strange and practical tips , Code up to seven lines , Each line is carefully annotated , Hope to be able to just learn Python Help novices .

 Insert picture description here

One 、 Filter the data in the sequence according to the conditions

  • Suppose there is a list of numbers data, Filter negative numbers in the list
data = [1, 2, 3, 4, -5]
  
#  Use list derivation 
result = [i for i in data if i >= 0]
  
#  Use  fliter  Filter function 
result = filter(lambda x: x >= 0, data)
 Copy code 
  • Students' math scores are stored in a dictionary , The score is greater than 80 Classmate
from random import randint
  
d = {x: randint(50, 100) for x in range(1, 21)}
r = {k: v for k, v in d.items() if v > 80}
 Copy code 

Two 、 Flip the key value pairs of the dictionary

  • Use zip() function

zip() Function to take iteratable objects as parameters , Package the corresponding elements in the object into tuples , Then return a list of these tuples .

from random import randint, sample
  
s1 = {x: randint(1, 4) for x in sample("abfcdrg", randint(1, 5))}
d = {k: v for k, v in zip(s1.values(), s1.keys())}
 Copy code 

3、 ... and 、 Count the frequency of elements in the sequence

  • In a random sequence , Find the most frequent 3 Elements , How often do they appear

Method 1:

#  You can use a dictionary to count , Key the data in the list , In terms of the number of occurrences 
from random import randint
  
#  Construct random sequence 
data = [randint(0, 20) for _ in range(30)]
  
#  The number of times a number appears in the list 
d = dict.fromkeys(data, 0)
  
for v in d:
  d[v] += 1
 Copy code 

Method 2:

#  Use it directly  collections  Below the module  Counter  object 
from collections import Counter
from random import randint
  
data = [randint(0, 20) for _ in range(30)]
  
c2 = Counter(data)
  
#  Number of occurrences of query elements 
c2[14]
  
#  The highest frequency of Statistics 3 Number 
c2.most_common(3)
 Copy code 
  • Count the words in an English article , Find the word with the highest number of occurrences and the number of occurrences
import re
from collections import Counter
  
#  Count the frequency of Chinese and English words in an article 
with open("test.txt", "r", encoding="utf-8") as f:
  d = f.read()
  
#  A list of all the words 
total = re.split("\W+", d)
result = Counter(total)
print(result.most_common(10))
 Copy code 

Four 、 According to the size of the dictionary values , Sort the items in the dictionary

  • For example, the math scores of middle school students in the class are stored in the form of a dictionary , Please rank your math scores from top to bottom

Method 1:

#  utilize  zip  Convert dictionary to tuple , Reuse  sorted  Sort 
from random import randint
  
data = {x: randint(60, 100) for x in "xyzfafs"}
sorted(data)
data = sorted(zip(data.values(), data.keys()))
 Copy code 

Method 2:

#  utilize  sorted  Functional  key  Parameters 
from random import randint
  
data = {x: randint(60, 100) for x in "xyzfafs"}
data.items()
sorted(data.items(), key=lambda x: x[1])
 Copy code 

5、 ... and 、 Find common keys in multiple dictionaries

  • The actual scene : In the football league , Count the players who score in every round

The first round :{"C ROM. ": 1, " Suarez ":2, " Torres ": 1..}

The second round :{" Neymar ": 1, " Lionel messi ":2, " Mbappé ": 3..}

The third round :{" Mbappé ": 2, "C ROM. ":2, " Neymar ": 1..}

from random import randint, sample
from functools import reduce
  
#  Simulate a random number of goals and players 
s1 = {x: randint(1, 4) for x in sample("abfcdrg", randint(1, 5))}
s2 = {x: randint(1, 4) for x in sample("abfcdrg", randint(1, 5))}
s3 = {x: randint(1, 4) for x in sample("abfcdrg", randint(1, 5))}
  
#  First get the dictionary  keys, Then take every round of the game  key  Intersection . Because the number of rounds is variable , So use  map  To batch operate 
# map(dict.keys, [s1, s2, s3])
  
#  And then all the way to the intersection , Use  reduce  function 
reduce(lambda x, y: x & y, map(dict.keys, [s1, s2, s3]))
 Copy code 

Your support is my driving force for continuous renewal ,( give the thumbs-up , Focus on , Comment on )

 Insert picture description here

Click to collect  q Group : 675240729( Pure technology exchange and resource sharing ) Take it by yourself .

① Industry consulting 、 Professional answers ②Python Development environment installation tutorial ③400 Self study video ④ Software development vocabulary ⑤ The latest learning roadmap ⑥3000 Multiple copies Python e-book

copyright notice
author[Yunyun yyds],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202010541191778.html

Random recommended