Python小技巧 格式化字符串 yield 列表解析式 Enumerate 字节合并 三元运算符 序列解包 with打开文件

python 小技巧

变量直接交换

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

格式化字符串

name = "冯牛逼"
age = 18
直接输出
print("我的名字是" + name + "。我的年龄是" + str(age) + "。")
我的名字是冯牛逼。我的年龄是18。
使用%
print("我的名字是%s。我的年龄是%d。"%(name, age))
我的名字是冯牛逼。我的年龄是18。
Format()方法
print("我的名字是{}。我的年龄是{}。".format(name, age))
我的名字是冯牛逼。我的年龄是18。

format方法在需要重复使用变量的时候可以加上索引

print("我的名字是{0}。我的年龄是{1},也就是我{1}岁了。".format(name, age))
我的名字是冯牛逼。我的年龄是18,也就是我18岁了。

python3.6版本强化后的format版本可以直接写入,即f-string格式,需要在前加上 f""

print(f"我的名字是{name}。我的年龄是{age},明年我{age + 1}岁了。")
我的名字是冯牛逼。我的年龄是18,明年我19岁了。

Yield语法

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可以在使用函数时无需等待函数执行完成再输出,可以边执行边输出,且同时不会影响函数的执行。
在一些需要长时间运行的程序中很方便
同时在一些有概率失败的爬虫程序中也可以逐步保存不至于前功尽弃

列表解析式 List Comprehension

遍历

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"常规遍历方法{namesfori},列表解析式方法{namesCompre}。")
常规遍历方法['FYZ', 'YJK', 'XHR', 'ZC'],列表解析式方法['FYZ', 'YJK', 'XHR', 'ZC']。
遍历时,可以 reversed(names) 反向遍历, 也可以sorted(names)排序后遍历

筛选

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

print(f"常规筛选方法{namesforif},列表解析式方法{namesCompreif}。")
常规筛选方法['fyz'],列表解析式方法['fyz']。

Enumerate 函数

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

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

enumerate 函数可以在迭代时同时获取索引值

字典的合并

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"常规方法合并{c}\n解包合并{d}")
常规方法合并{'fyz': 'dalao', 'yjk': 'wuqing', 'xhr': 'niubi', 'zc': 'laji'}
解包合并{'fyz': 'dalao', 'yjk': 'wuqing', 'xhr': 'niubi', 'zc': 'laji'}

三元运算符

a = 6
b = 8

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

max3 = a if a > b else b

print(f"ifelse方式{max1}\n三元运算符方式{max3}")
ifelse方式8
三元运算符方式8

序列解包

name = "Feng YuZhen"

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

f, l = name.split() #split()默认以空格分开

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

with打开文件

类似于java中的 try (source)

f = open("txt.txt", "r")
s = f.read()
f.close() #文件打开后要手动关闭

with open("txt.txt", "r") as f: # 自动关闭
    s = f.read()

python之禅

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!

Python 之禅,作者 Tim Peters

  • 美丽胜于丑陋。

  • 显式优于隐式。

  • 简单胜于复杂。

  • 复杂总比隐晦好。

  • 扁平比嵌套好。

  • 稀疏比密集好。

  • 可读性很重要。

  • 特殊情况不足以打破规则。

  • 虽然实用性胜过纯度。

  • 错误永远不应该静默传递。

  • 除非明确沉默。

  • 面对模棱两可,拒绝猜测的诱惑。

  • 应该有一种——最好只有一种——明显的方法来做到这一点。

  • 尽管这种方式起初可能并不明显,除非您是荷兰人。

  • 现在总比没有好。

  • 尽管现在永远不会比正确更好。

  • 如果实现很难解释,那是个坏主意。

  • 如果实现很容易解释,这可能是一个好主意。

  • 命名空间是一个很棒的想法——让我们做更多的事情!

posted @ 2021-07-26 11:07  SKPrimin  阅读(62)  评论(0编辑  收藏  举报