Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the new features of Python 3.9

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the new functions of Python 3.9". In daily operation, I believe that many people have doubts about the new features of Python 3.9. the editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "what are the new features of Python 3.9"! Next, please follow the editor to study!

1. Dictionary (merge & update) operator

Dictionary is one of the most basic data structures in Python, and performance is constantly optimized with the iteration of the python version.

In Python3.9, the merge (|) and update (| =) operators have been added to the dict class. These updates improve the existing dict.update and {* * D1 recording * d2} methods.

The traditional method of merging dictionaries:

> > pycon = {2016: "Portland", 2018: "Cleveland"} # dictionary 1 > europython = {2017: "Rimini", 2018: "Edinburgh", 2019: "Basel"} # dictionary 2 # method 1 > > {* * pycon, * * europython} {2016: 'Portland', 2018:' Edinburgh', 2017: 'Rimini', 2019:' Basel'} # method 2 > > merged = pycon.copy () > > for key, value in europython.items (): Merged [key] = value... > > merged {2016: 'Portland', 2018:' Edinburgh', 2017: 'Rimini', 2019:' Basel'}

Both methods merge dictionaries without changing the original data. Note that "Cleveland" in dictionary 1 has been overwritten by "Edinburgh" in merged dictionary 2.

You can also update the dictionary 1:

> pycon.update (europython) > pycon {2016: 'Portland', 2018:' Edinburgh', 2017: 'Rimini', 2019:' Basel'}

The new version of Python introduces two new dictionary operators: merge (|) and update (| =). You can use | merge two dictionaries, and | = is used to update the dictionary:

> > pycon = {2016: "Portland", 2018: "Cleveland"} > europython = {2017: "Rimini", 2018: "Edinburgh", 2019: "Basel"} > pycon | europython # merge {2016: 'Portland', 2018:' Edinburgh', 2017: 'Rimini', 2019:' Basel'} > pycon | = europython # Update > > pycon {2016: 'Portland', 2018:' Edinburgh',: 'Rimini', 2019:' Basel'}

D1 | D2 and {* * D1 key * D2} are used to merge dictionaries and merge sets. If the same Dictionary is encountered, the latter will overwrite the former.

One of the advantages of using | is that it applies to dictionary-like types and maintains the original type after the merge:

> > from collections import defaultdict > europe = defaultdict (lambda: ", {" Norway ":" Oslo "," Spain ":" Madrid "}) > africa = defaultdict (lambda:", {" Egypt ":" Cairo "," Zimbabwe ":" Harare "}) > > europe | africa defaultdict (, {'Norway':' Oslo', 'Spain':' Madrid', 'Egypt':' Cairo', 'Zimbabwe':' Harare'}) > > {* * europe * * africa} {'Norway':' Oslo', 'Spain':' Madrid', 'Egypt':' Cairo', 'Zimbabwe':' Harare'}

| = is used to update the dictionary, similar to .update ():

> > libraries = {... Collections: Container datatypes,... "math": "Mathematical functions",...} > libraries | = {"zoneinfo": "IANA time zone support"} > libraries {'collections':' Container datatypes', 'math':' Mathematical functions', 'zoneinfo':' IANA time zone support'}

| = you can also use data structures similar to dictionaries to update:

> libraries | = [("graphlib", "Functionality for graph-like structures")] > libraries {'collections':' Container datatypes', 'math':' Mathematical functions', 'zoneinfo':' IANA time zone support', 'graphlib':' Functionality for graph-like structures'}

two。 Delete string prefixes and suffixes

In Python 3.9, you can use .removeprefix () and .removesuffix () to delete the beginning or end of a string, respectively:

> "three cool features in Python" .removesuffix ("Python") 'three cool features in' > "three cool features in Python" .removeprefix ("three")' cool features in Python' > "three cool features in Python" .removeprefix ("Something else") 'three cool features in Python'

Some people may say that the .strip method is also fine, but this method will result in erroneous deletion:

> "three cool features in Python" .strip ("Python") 'ree cool features i'

As you can see, you obviously want to delete the word python at the end, but the beginning of the there is also deleted-Th.

So .removeprefix () and .removesuffix () may be more precise.

3. Zoneinfo time zone module

Zoneinfo is a new module introduced by python3.9, and zoneinfo can access the Internet number allocation Authority (IANA) time zone database. IANA updates its database several times a year, which is the most authoritative source of time zone information.

Using zoneinfo, you can get objects that describe any time zone in the database:

> from zoneinfo import ZoneInfo > ZoneInfo ("America/Vancouver") zoneinfo.ZoneInfo (key='America/Vancouver') > > from zoneinfo import ZoneInfo > from datetime import datetime, timedelta > # Daylight time > dt = datetime (2020, 10, 31, 12) Tzinfo=ZoneInfo ("America/Los_Angeles") > print (dt) 2020-10-31 12:00:00-07:00 > dt.tzname () 'PDT' > > # Standard time > dt + = timedelta (days=7) > print (dt) 2020-11-07 12:00:00-08:00 > print (dt.tzname ()) PST

4. Built-in collection types are used for type prompts

In the type hint, you can now use built-in collection types (such as list and dict) as generic types without having to import the corresponding uppercase types (such as List or Dict) from typing.

Def greet_all (names: list [str])-> None: for name in names: print ("Hello", name)

5. Topological sorting

Python 3.9 adds a new module, graphlib, which contains the graphlib.TopologicalSorter class to provide the ability to perform topological sorting.

> > dependencies = {... Realpython-reader: {"feedparser", "html2text"},... "feedparser": {"sgmllib3k"},... > from graphlib import TopologicalSorter > ts = TopologicalSorter (dependencies) > list (ts.static_order ()) ['html2text',' sgmllib3k', 'feedparser',' realpython-reader']

6. Least common multiple (LCM)

Python has long had the ability to calculate the greatest common divisor (GCD) of two numbers:

> import math > math.gcd (49,14) 7

The least common multiple (LCM) is related to the maximum common divisor (GCD). You can define LCM according to GCD:

Def lcm (num1, num2):... If num1 = = num2 = = 0:... Return 0... Return num1 * num2 / / math.gcd (num1, num2). > > lcm (49,14) 98

In Python 3.9, you no longer need to define your own LCM function, it adds the ability to calculate the least common multiple:

> import math > math.lcm (49,14) 98

7. A more powerful Python parser

One of the coolest features of Python 3.9 is one that people don't notice in everyday programming: parser updates. The parser is the basic component of the Python interpreter. In the latest version, the parser has been rebuilt.

Python has previously used the LL (1) parser to parse the source code into a parsing tree. You can think of a LL (1) parser as a parser that reads one character at a time and interprets the source code without backtracking.

The new interpreter is based on PEG (parsing expression grammar), not LL (1). The performance of the new parser is comparable to that of the old parser, and PEG is more flexible than LL (1) when designing new language features.

In the entire standard library, the PEG parser is slightly faster, but also uses more memory. In fact, it's hard to perceive performance when using a new parser.

At this point, the study on "what are the new features of Python 3.9" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report