Python tips format string yield list parse Enumerate byte merge ternary operator sequence unpack with open file

python tips

Direct exchange of variables

a = 1
b = 2
a, b = b, a
print(f'a = {a}\nb = {b}')
a = 2
b = 1

format string

name = "Feng Niubi"
age = 18
Direct output
print("My name is" + name + ". My age is" + str(age) + ". ")
My name is Feng Niubi. My age is 18.
Use%
print("My name is%s. My age is%d. "%(name, age))
My name is Feng Niubi. My age is 18.
Format() method
print("My name is{}. My age is{}. ".format(name, age))
My name is Feng Niubi. My age is 18.

The format method can add an index when variables need to be reused

print("My name is{0}. My age is{1},That's me{1}Years old.".format(name, age))
My name is Feng Niubi. My age is 18,I'm 18.

python3. The enhanced format version of version 6 can be written directly, that is, f-string format, which needs to be preceded by F ""

print(f"My name is{name}. My age is{age},Next year I{age + 1}Years old.")
My name is Feng Niubi. My age is 18,I'll be 19 next year.

Yield grammar

nums = [6, 7, 8]
def fori(lista):
    numa = []
    for i in lista:
        i += 1
        numa.append(i)
    return numa

for i in fori(nums):
    print(i)
7
8
9
nums = [6, 7, 8]
def fori(lista):
    for i in lista:
        i += 1
        yield i
    return 0

for i in fori(nums):
    print(i)
7
8
9

yield can output while executing a function without waiting for the function to be executed, and it will not affect the execution of the function.
It is very convenient in some programs that need to run for a long time
At the same time, it can also be saved step by step in some crawler programs with probability of failure, so as not to waste all previous efforts

List resolution

ergodic

names = ["fyz", "yjk", "xhr", "zc"]

namesfori = []
for i in range(len(names)):
    namesfori.append(names[i].upper())
    
namesCompre = [i.upper() for i in names]

print(f"General traversal method{namesfori},List parsing method{namesCompre}. ")
General traversal method['FYZ', 'YJK', 'XHR', 'ZC'],List parsing method['FYZ', 'YJK', 'XHR', 'ZC']. 
Traversal time,sure reversed(names) reverse traversal , it's fine too sorted(names)Traversal after sorting

screen

namesforif = []
for name in names:
    if name.endswith("z"):
        namesforif.append(name)
        
namesCompreif = [i for i in names if i.endswith("z")]

print(f"General screening method{namesforif},List parsing method{namesCompreif}. ")
General screening method['fyz'],List parsing method['fyz']. 

Enumerate function

names = ["fyz", "yjk", "xhr", "zc"]

for i, name in enumerate(names):
    print(i, name)
0 fyz
1 yjk
2 xhr
3 zc

The enumerate function can get the index value at the same time during iteration

Dictionary merging

a = {"fyz":"dalao", "yjk":"wuqing"}
b = {"xhr":"niubi", "zc":"laji"}
c = {}
for key in a:
    c[key] = a[key]
for key in b:
    c[key] = b[key]

d = {**a, **b}
print(f"Conventional method merge{c}\n Unpacking and merging{d}")
Conventional method merge{'fyz': 'dalao', 'yjk': 'wuqing', 'xhr': 'niubi', 'zc': 'laji'}
Unpacking and merging{'fyz': 'dalao', 'yjk': 'wuqing', 'xhr': 'niubi', 'zc': 'laji'}

Ternary operator

a = 6
b = 8

if a > b:
    max1 = a
else:
    max1 = b

max3 = a if a > b else b

print(f"ifelse mode{max1}\n Ternary operator mode{max3}")
ifelse Mode 8
 Ternary operator mode 8

Sequence unpacking

name = "Feng YuZhen"

namelist = name.split()
first_name = namelist[0]
last_name = namelist[1]

f, l = name.split() #split() is separated by spaces by default

print(f"{first_name},{last_name}\n{f},{l}")
Feng,YuZhen
Feng,YuZhen

with open file

It is similar to try (source) in java

f = open("txt.txt", "r")
s = f.read()
f.close() #Close the file manually after opening it

with open("txt.txt", "r") as f: # Auto off
    s = f.read()

python Zen

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Zen in Python by Tim Peters

  • Beauty is better than ugliness.

  • Explicit is better than implicit.

  • Simplicity is better than complexity.

  • Complexity is better than complexity.

  • Flat is better than nested.

  • Sparse is better than dense.

  • Readability is important.

  • Special circumstances are not enough to break the rules.

  • Although practicality is better than purity.

  • Errors should never be passed silently.

  • Unless explicitly silent.

  • In the face of ambiguity, refuse the temptation to guess.

  • There should be one - preferably only one - obvious way to do this.

  • Although this may not be obvious at first, unless you are Dutch.

  • Now is better than nothing.

  • Although it will never be better than right now.

  • If implementation is hard to explain, that's a bad idea.

  • If the implementation is easy to explain, this may be a good idea.

  • Namespaces are a great idea -- let's do more!

Keywords: Python

Added by Solarpitch on Fri, 14 Jan 2022 06:05:16 +0200