Python基础:被低估的"偷懒"技巧,新手必学!

刚入门Python,写代码总在"重复造轮子"?这几个进阶基础知识点,不用啃复杂文档,练熟直接少走弯路,代码简洁又高效~

1. 集合(set):去重+判断的"极速工具"

还在靠列表遍历去重?集合自带去重属性,效率翻倍:

python 复制代码
  
# 列表去重(繁琐且慢)
nums = [1, 2, 2, 3, 3, 3]
unique_nums = []
for num in nums:
    if num not in unique_nums:
        unique_nums.append(num)
print(unique_nums)  # 输出: [1,2,3]

# 集合去重(一行搞定)
unique_nums = list(set(nums))
print(unique_nums)  # 输出: [1,2,3](顺序不保证,需排序可加sorted())
 
 
判断元素是否存在,集合比列表快100倍(大数据量更明显):
 
fruit_set = {"apple", "banana", "cherry"}
print("apple" in fruit_set)  # 输出: True(O(1)时间复杂度)

2. enumerate:循环时"顺便"拿索引

遍历列表想同时要索引和元素?别用 range(len()) 了:

python 复制代码
  
fruits = ["apple", "banana", "cherry"]
# 传统写法(麻烦且不优雅)
for i in range(len(fruits)):
    print(f"索引{i}:{fruits[i]}")

# enumerate写法(直接获取索引+元素)
for idx, fruit in enumerate(fruits, start=1):  # start指定索引起始值
    print(f"第{idx}个水果:{fruit}")  # 输出: 第1个水果:apple...

3. zip:多列表"配对"的神器

想同时遍历多个列表?zip直接打包,不用手动索引对齐:

python 复制代码
  
names = ["张三", "李四", "王五"]
scores = [85, 92, 78]
subjects = ["数学", "语文", "英语"]

# 传统写法(容易出错)
for i in range(len(names)):
    print(f"{names[i]} {subjects[i]}:{scores[i]}分")

# zip打包(简洁且安全)
for name, subject, score in zip(names, subjects, scores):
    print(f"{name} {subject}:{score}分")  # 输出: 张三 数学:85分...
 
 
打包后转字典更方便:
 
python
  
student_scores = dict(zip(names, scores))
print(student_scores)  # 输出: {'张三':85, '李四':92, '王五':78}

这三个技巧都是日常开发高频用到的,看似简单却能解决很多冗余场景~ 赶紧复制代码实测,练熟直接提升代码整洁度!

相关推荐
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee1 天前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay1 天前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤1 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean1 天前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽1 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户60648767188962 天前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api
只与明月听2 天前
RAG深入学习之Chunk
前端·人工智能·python