6

【Python | 进阶】提高你的Python技能,9个让代码更简洁、更快的秘密技巧, 确定不来...

 1 year ago
source link: https://blog.51cto.com/u_15691039/6986881
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【Python | 进阶】提高你的Python技能,9个让代码更简洁、更快的秘密技巧, 确定不来看看?

精选 原创

计算机魔术师 2023-08-06 20:56:48 ©著作权

文章标签 ci 迭代 python 文章分类 Python 后端开发 阅读数194

【Python | 进阶】提高你的Python技能,9个让代码更简洁、更快的秘密技巧, 确定不来看看?_python

🤵♂️ 个人主页:  @AI_magician 📡主页地址: 作者简介:CSDN内容合伙人,全栈领域优质创作者。 👨💻景愿:旨在于能和更多的热爱计算机的伙伴一起成长!!🐱🏍 🙋♂️声明:本人目前大学就读于大二,研究兴趣方向人工智能&硬件(虽然硬件还没开始玩,但一直很感兴趣!希望大佬带带)

【Python | 进阶】提高你的Python技能,9个让代码更简洁、更快的秘密技巧, 确定不来看看?_ci_02

在使用python,其实有着许许多多所不为人知的python技巧,这些小技巧可以让代码更简洁高效,应该多加利用! 这里就和分享99个Python的小技巧 (持续更新!!!!)

  1. 使用enumerate()获取索引。在for循环中使用enumerate可以同时获取索引和值,非常方便:
for i, v in enumerate(list_name):
    print(i, v)
  1. 使用collections模块的defaultdict创建字典。可以不用检查key是否存在,直接赋值:
from collections import defaultdict

d = defaultdict(list) # 默认值
d['a'].append(1) 
print(d) # {'a': [1]}
  1. 使用zip()同时遍历两个列表。可以同时处理两个列表:
names = ['a', 'b']
ages = [20, 30]

for name, age in zip(names, ages): # 变成元组对
    print(name, age)
  1. 使用reversed()反向遍历。不需要先reverse列表:
for i in reversed(range(1, 10)):
    print(i)
  1. 使用set去重。可以很方便的对列表去重:
list_with_duplicates = [1, 2, 1, 3]
list_without_duplicates = list(set(list_with_duplicates))
  1. 使用any()和all()判断列表。any()只要有一个True就返回True,all()需要全部True才返回True
  2. 使用with语句自动关闭文件。不需要try-finally来关闭文件:
with open('file.txt') as f:
    data = f.read()

文件会在with代码块结束后自动关闭。

  1. 使用列表推导式(List Comprehensions)来简化列表的创建。它可以在一行代码中创建一个新的列表,非常方便:
squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]
  1. 使用字典推导式(Dictionary Comprehensions)来简化字典的创建。类似于列表推导式,可以在一行代码中创建一个新的字典:
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
  1. 使用**装饰器(Decorators)**来修改函数的行为。装饰器可以在不修改原函数代码的情况下,为函数添加额外的功能:
def uppercase_decorator(func):
    def wrapper():
        result = func()
        return result.upper()
    return wrapper

@uppercase_decorator # 实现一个大写装饰器,对所有返回为string的大写
def greet():
    return "hello"

print(greet())  # "HELLO"
  1. 使用生成器(Generators)来按需生成数据。生成器可以节省内存,并且可以在需要时逐个生成值:
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
print(next(fib))  # 0
print(next(fib))  # 1
print(next(fib))  # 1
print(next(fib))  # 2
  1. 使用collections模块中的Counter类来统计元素出现的次数。它可以接受一个可迭代对象,并返回一个字典,其中键是元素,值是元素出现的次数:
from collections import Counter

fruits = ['apple', 'banana', 'orange', 'apple', 'banana', 'apple']
fruit_counts = Counter(fruits)
print(fruit_counts)

# 输出:
# Counter({'apple': 3, 'banana': 2, 'orange': 1})
  1. 使用itertools模块中的函数来进行迭代操作。它提供了一些有用的函数,如排列组合、无限迭代器等:
import itertools

# 排列组合
letters = ['a', 'b', 'c']
perms = itertools.permutations(letters, 2)
print(list(perms))  # [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

# 无限迭代器
count = itertools.count(start=1, step=2)
print(next(count))  # 1
print(next(count))  # 3
print(next(count))  # 5
  1. 使用logging模块来进行日志记录。它可以帮助你在程序中添加日志信息,以便调试和错误追踪:
import logging

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
  1. 通过 * 创建列表

通过使用乘法运算符 * 来复制列表中的元素来实现的。下面是一个示例,展示了如何使用 [None] * 3 创建一个包含3个 None 元素的列表:

my_list = [None] * 3
print(my_list)
[None, None, None]
  1. 对于数字,python3.9版本,可以用 3000表示为 3,000 格式更加规范
  2. 使用__name__ == "main"检查是否在主程序中运行。这可以让你的代码既可以作为模块导入,也可以直接运行:
def main():
    print("Running as main program")

if __name__ == "__main__":
    main()
  1. 使用__import__()函数来动态导入模块。这比使用import语句更灵活:
module_name = input("Enter module name: ")
module = __import__(module_name)
  1. 使用locals()和globals()函数获取局部变量和全局变量。这对调试很有用:
x = 50  

print(locals()) 
# {'x': 50}

print(globals())
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f9c4c4c4e80>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 50}
  1. 使用sys.setrecursionlimit()函数来增加递归限制。默认是1000:
import sys

sys.setrecursionlimit(2000)
  1. 使用__import__('os').name来获取操作系统名称。这比import os更简单:
import os
print(os.name)

# 等同于

print(__import__('os').name)
  1. 使用__import__('random').randint(1, 100)来生成1-100的随机整数。
  2. 使用__import__('time').sleep(1)来让程序暂停1秒。
  3. 使用__import__('json').dumps()和__import__('json').loads()来序列化和反序列化JSON。
  4. 使用__import__('pickle').dump()和__import__('pickle').load()来序列化和反序列化任意Python对象。
  5. 使用__import__('sys').exit()来立即退出程序。
  6. 使用tracebackhide = True隐藏traceback。这对开发工具很有用:
def func():
    __tracebackhide__ = True 
    raise Exception("hidden")

func()  # No traceback
  1. 使用__debug__检查是否在调试模式下运行。这对条件编译很有用:
if __debug__:
    print("Running in debug mode")
  1. 使用metaclass定义元类。这允许自定义类的创建:
class Meta(type):
    pass

class MyClass(object):
    __metaclass__ = Meta
  1. 使用__del__定义析构函数。这在对象被垃圾回收时调用:
class Point:
    def __del__(self):
        print("Point destroyed")
  1. 使用__getattr__和__setattr__自定义属性访问。这允许隐藏属性:
class Point:
    def __getattr__(self, attr):
        ...
    def __setattr__(self, attr, value): 
        ...
  1. 使用__iter__和__next__定义可迭代对象。这让你的类可以使用for循环:
class Point:
    def __iter__(self):
        ... 
    def __next__(self):
        ...
  1. 使用__enter__和__exit__定义上下文管理器。这让你的类可以使用with语句:
class Point:
    def __enter__(self):
        ...
    def __exit__(self, exc_type, exc_value, traceback):
        ...
  1. 使用逗号来分隔print语句打印多条语句。
print(1,2,3)
# 1 2 3
  1. 通过设置宽度和填充字符格式化print输出。
print("{:10}".format(123)) 
# "       123"
print("{:^10}".format(123))  
# "   123    " 
print("{:*>10}".format(123))
# "*****123"
  1. 使用.startswith().endswith() 来检查字符串。
" Hello".startswith("H") 
# True
"Hello".endswith("o")
# True
  1. 使用dict.get() 来获取字典值,避免KeyError。
d = {"name": "John"}
d.get("name")    # John
d.get("age")     # None
  1. 在循环中用else来代替flag变量。
for n in range(2, 10):
   for x in range(2, n):
      if n % x == 0:
         break
   else:
       print(n)

这些小技巧可以让代码更简洁高效,多加利用!

【Python | 进阶】提高你的Python技能,9个让代码更简洁、更快的秘密技巧, 确定不来看看?_python_03

🤞到这里,如果还有什么疑问🤞
					🎩欢迎私信博主问题哦,博主会尽自己能力为你解答疑惑的!🎩
					 	 🥳如果对你有帮助,你的赞是对博主最大的支持!!🥳

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK