【Python基础】13个你不知道的Python技巧

前言

  • Python 是顶级编程语言之一,它具有许多程序员从未使用过的许多隐藏功能。本文,我将分享13个你可能从未使用过的 Python 特性。
    在这里插入图片描述

包含编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!!!

1.按步长取数

知识点: “list[start:stop:step]”
  • start: 开始索引, 默认为0
  • end: 结束索引, 默认为列表长度
  • step: 步长, 默认为1, 可以为负数, 如果为负数, 则为倒序.
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]   
print(data[::2]) # [1, 3, 5, 7, 9]   
print(data[::-1]) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]   
print(data[2:7:-2]) # [] ⚠️注意:步长为负数时,结果为空   
print(data[7:1:-2]) # [8,6,4] # ⚠️ index 属于 [7 -> 1),步长为2。

2.find 方法

知识点:“list.find(obj, [start, [stop]])”
  • list: 列表或者字符串
  • obj: 查找的元素
  • start: 开始索引, 默认为0
  • stop: 结束索引, 默认为列表长度
找不到返回-1
x = "Hello From Python"   
print(x.find("o")) # 4   
print(x.find("o", 5)) # 8   
print(x.find("From Python")) # 6   
print(x.find("No exist")) # -1   

3. iter() 和 next()

# iter() 函数用于将一个可迭代对象转换为一个迭代器   
# next() 函数用于获取迭代器的下一个返回值   
values = [1, 3, 4, 6]   
values = iter(values)   
print(next(values)) # 1   
print(next(values)) # 3   
print(next(values)) # 4   
print(next(values)) # 6   
print(next(values)) # StopIteration   

4.测试文档

  • “Doctest"功能将让您测试您的功能并显示您的测试报告。如果您检查下面的示例,您需要在三重引号中编写一个测试参数,其中”>>>"是固定的语法,你可以增加测试案例,并运行它!如下所示:
# Doctest   
from doctest 
import testmod        
def Mul(x, y) -> int:
"""This function returns the mul of x and y argumets incoking the function followed by expected output: 
>>> Mul(4, 5)20>>> Mul(19, 20)39"""     
return x * y   
testmod(name='Mul')     
# 输出如下:"""
**********************************************************************   
File "main.py", line 10, in Mul.Mul Failed example:Mul(19, 20) Expected:39 Got:380   
**********************************************************************   
1 items had failures:      
1 of   
2 in Mul.Mul   
***Test Failed*** 
1 failures.   """   

5.yield

  • "yield"语句是Python的另一个令人惊奇的特性,它的工作方式类似于"return"语句。但它不是终止函数并返回,而是返回到它返回给调用者的地方。
  • "yield"返回的是一个生成器。可以使用"next()"函数来获取生成器的下一个值。也可以使用"for"循环来遍历生成器。
def func():       
print(1)       
yield "a"       
print(2)       
yield "aa"       
print(3)       
yield "aaa"      
print(list(func())) ## ['a', 'aa', 'aaa']   
for x in func():       
print(x)   

6.字典缺失键的处理

 dic = {1: "x", 2: "y"}  # 不能使用 
dict_1[3] 获取值   
print(dic[3]) # Key Error # 使用 get() 方法获取值   
print(dic.get(3)) # None   
print(dic.get(3, "No")) # No   

7.for-else、while-else

  • 你知道 Python 支持带有"for-else"、 "while-else"吗?这个"else"语句会在你的循环没有中断地运行完后执行,如果中途中断了循环,则不会执行。
# for-else   
for x in range(5):       
print(x)   
else:       
print("Loop Completed") # executed   # while-else   
i = 0    
while i < 5:       
break else:       
print("Loop Completed") # Not executed   

8.f-string的强大

a = "Python"   
b = "Job"   
# Way 1   
string = "I looking for a {} Programming {}".format(a, b)   
print(string) 
# I looking for a Python Programming Job   
#Way 2   
string = f"I looking for a {a} Programming {b}"   
print(string) # I looking for a Python Programming Job   

9.改变递归深度

  • 这是 Python 的另一个重要特性,它可以让您设置 Python 程序的递归限制。看一下下面的代码示例以更好地理解:
import sys   
print(sys.getrecursionlimit()) # 1000 默认值   
sys.setrecursionlimit = 2000   
print(sys.getrecursionlimit) # 2000   

10.条件赋值

  • 条件赋值功能使用三元运算符,可以在特定条件下为变量赋值。看看下面的代码示例:
x = 5 if 2 > 4 else 2   
print(x) # 2   
y = 10 if 32 > 41 else 24   
print(y) # 24   

11.参数解包

  • 您可以解压缩函数中的任何可迭代数据参数。看看下面的代码示例:
def func(a, b, c):       
print(a, b, c)      
x = [1, 2, 3]   
y = {'a': 1, 'b': 2, 'c': 3}   
func(*x) # 1 2 3   
func(**y) # 1 2 3   

12.呼唤世界(没啥用)

import __hello__ 
# 你猜输出啥?   
# other code   
import os   
print(os) 
# <module 'os' from '/usr/lib/python3.6/os.py'>   

13.多行字符串

  • 此功能将向您展示如何编写没有三重引号的多行字符串。看看下面的代码示例:
# 多行字符串   
str1= "Are you looking for free Coding " \   "Learning material then " \   "welcome to py2fun.com"   
print(str1) 
# Are you looking for free Coding Learning material then welcome to Medium.com  
# 三重引号字符串   
str2 = 
"""Are you looking for free Coding Learning material then welcome to py2fun.com """   
print(str2) #和上面的是不同的,换行也会被输出。   

总结

  • 最后希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!

文末福利

  • 最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀

包含编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值