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 .
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 )
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
The sidebar is recommended
- Django paging (II)
- Concurrent. For Python concurrent programming Futures or multiprocessing?
- Programmers over the age of 25 can't know a few Chinese herbal medicines. Python crawler lessons 9-9
- Python crawler from introduction to pit full series of tutorials (detailed tutorial + various practical combat)
- The second bullet of class in Python
- Python object oriented programming 03: class inheritance and its derived terms
- How IOS developers learn Python Programming 13 - function 4
- Python crawler from introduction to mastery (VI) form and crawler login
- Python crawler from entry to mastery (V) challenges of dynamic web pages
- Deeply understand pandas to read excel, TXT, CSV files and other commands
guess what you like
-
Daily python, Chapter 18, class
-
"I just want to collect some plain photos in Python for machine learning," he said. "I believe you a ghost!"
-
Django view
-
Python implements filtering emoticons in text
-
When winter comes, python chooses a coat with temperament for mom! Otherwise, there's really no way to start!
-
Python crawler - get fund change information
-
Highlight actor using Python VTK
-
Python crawler actual combat: crawling southern weekend news articles
-
leetcode 406. Queue Reconstruction by Height(python)
-
leetcode 1043. Partition Array for Maximum Sum (python)
Random recommended
- Python * * packaging and unpacking details
- Python realizes weather query function
- Python from 0 to 1 (day 12) - Python data application 2 (STR function)
- Python from 0 to 1 (day 13) - Python data application 3
- Numpy common operations of Python data analysis series Chapter 8
- How to implement mockserver [Python version]
- Van * Python! Write an article and publish the script on multiple platforms
- Python data analysis - file reading
- Python data De duplication and missing value processing
- Python office automation - play with browser
- Python series tutorial 127 -- Reference vs copy
- Control flow in Python: break and continue
- Teach you how to extract tables in PDF with Python
- leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal(python)
- leetcode 1338. Reduce Array Size to The Half(python)
- Object oriented and exception handling in Python
- How to configure load balancing for Django service
- How to embed Python in go
- Python Matplotlib drawing graphics
- Python object-oriented programming 05: concluding summary of classes and objects
- Python from 0 to 1 (day 14) - Python conditional judgment 1
- Several very interesting modules in Python
- How IOS developers learn Python Programming 15 - object oriented programming 1
- Daily python, Chapter 20, exception handling
- Understand the basis of Python collaboration in a few minutes
- [centos7] how to install and use Python under Linux
- leetcode 1130. Minimum Cost Tree From Leaf Values(python)
- leetcode 1433. Check If a String Can Break Another String(python)
- Python Matplotlib drawing 3D graphics
- Talk about deep and shallow copying in Python
- Python crawler series - network requests
- Python thread 01 understanding thread
- Analysis of earthquake distribution in the past 10 years with Python~
- You need to master these before learning Python crawlers
- After the old friend (R & D post) was laid off, I wanted to join the snack bar. I collected some data in Python. It's more or less a intention
- Python uses redis
- Python crawler - ETF fund acquisition
- Detailed tutorial on Python operation Tencent object storage (COS)
- [Python] comparison of list, tuple, array and bidirectional queue methods
- Go Python 3 usage and pit Prevention Guide