Here are five of Python’s weirdest practical tips, up to seven lines of code, carefully commented on each line, to help new Python learners.

Filter the data in the sequence based on the criteria

  • Suppose you have a list of numbers, data, and filter the negative numbers in the list
data = [1.2.3.4, -5]
  
# Use list derivations
result = [i for i in data if i >= 0]
  
Use the fliter filter function
result = filter(lambda x: x >= 0, data)
Copy the code
  • Students’ math scores are stored in a dictionary and those with a score greater than 80 are screened
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 the code

2. Flip the dictionary key-value pairs

  • Use the zip() function

The zip() function takes an iterable object as an argument, packs the corresponding elements of the object into tuples, and returns a list of those 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 the code

Third, the frequency of occurrence of elements in the statistical sequence

  • In a random sequence, find the three elements that occur most frequently, and how often they occur

Method 1:

# You can use a dictionary for statistics, using the data in the list as the key and the number of occurrences as the value
from random import randint
  
# Construct random sequence
data = [randint(0.20) for _ in range(30)]
  
# Number of occurrences of a number in a list
d = dict.fromkeys(data, 0)
  
for v in d:
  d[v] += 1
Copy the code

Method 2:

Use the Counter object directly under the Collections module
from collections import Counter
from random import randint
  
data = [randint(0.20) for _ in range(30)]
  
c2 = Counter(data)
  
# query the number of occurrences of elements
c2[14]
  
# 3 numbers with the highest statistical frequency
c2.most_common(3)
Copy the code
  • Make statistics of words in an English article, find the word with the highest frequency and the frequency of occurrence
import re
from collections import Counter
  
# Count the frequency of words in English and Chinese of an article
with open("test.txt"."r", encoding="utf-8") as f:
  d = f.read()
  
# List of all words
total = re.split("\W+", d)
result = Counter(total)
print(result.most_common(10))
Copy the code

Sort the items in the dictionary according to the size of the values in the dictionary

  • For example, the math scores of students in the class are stored in the form of dictionary. Please sort them in order of highest math scores

Method 1:

Use zip to convert dictionaries to tuples, and use sorted dictionaries to sort them
from random import randint
  
data = {x: randint(60.100) for x in "xyzfafs"}
sorted(data)
data = sorted(zip(data.values(), data.keys()))
Copy the code

Method 2:

Use the sorted function's key argument
from random import randint
  
data = {x: randint(60.100) for x in "xyzfafs"}
data.items()
sorted(data.items(), key=lambda x: x[1])
Copy the code

Find common keys in multiple dictionaries

  • Practical scenario: In a football league, players who score goals in each round are counted

First round: {” Ronaldo “: 1, “Suarez “:2,” Torres “: 1.. }

Second round: {” Neymar “: 1, “Messi “:2,” Mbappe “: 3.. }

Round 3: {” Mbappe “:2, “Ronaldo “:2,” Neymar “: 1.. }

from random import randint, sample
from functools import reduce
  
# Simulate random players who score goals and the number of goals scored
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 fetch the keys of the dictionary, then fetch the intersection of keys for each round of the match. Since the number of race rounds is variable, map is used for batch operation
# map(dict.keys, [s1, s2, s3])
  
Then keep accumulating the intersection, using the reduce function
reduce(lambda x, y: x & y, map(dict.keys, [s1, s2, s3]))
Copy the code

Your support is my motivation to keep updating, (likes, follows, comments)

Click on 🎁 q Group: 675240729 (pure technical exchange and resource sharing) to pick it up.

More than 3000 Python ebooks are available, including: (1) Professional advice, (2) Installation of Python development environment, (3) 400 self-taught videos, (4) Common vocabulary of software development, (5) the latest learning roadmap, (6) More than 3000 Python ebooks