摘要:Increase knowledge, leave a beautiful!
分享兴趣,传播快乐,
增长见闻,留下美好!
亲爱的您,这里是LearningYard新学苑。
今天小编为大家带来文章 “刘心向学(44):enumerate—— 拒绝手动计数,让循环自带索引”Share interest, spread happiness,
Increase knowledge, leave a beautiful!
Dear, this is LearningYard Academy.
Today, the editor brings you an article.
“Liu Xin Xiang Xue (44): enumerate — Stop Manual Counting, Let Loops Carry Their Own Index”二、引言(Introduction)
You’ve likely written code like this:
for i in range ( len (items)):
Or even more manually:
But Python’s philosophy says:
?)is a built-in function that takes an iterable (like a list, tuple, or string) and returns an iterator of tuples, where each tuple is (index, value).一句话:
In short:
五、实战应用案例(Practical Application Examples)
1. 查找元素的所有位置
Find All Positions of an Element
def find_all_positions(lst, target):return [i for i, x inenumerate(lst) if x == target]numbers = [1, 2, 3, 2, 4, 2]positions = find_all_positions(numbers, 2)print(positions) # [1, 3, 5]2. 生成带序号的菜单
Generate Numbered Menus
3. 与字符串结合:逐字符处理
With Strings: Process Characters with Position
text = "hello"for i, char inenumerate(text):print(f"Position {i}: '{char}'")# 输出:# Position 0: 'h'# Position 1: 'e'# ...4. 读取文件并打印行号
Read File with Line Numbers
5. 算法题:找出递增序列的起始索引
Algorithm: Find Start of Increasing Sequence
六、高级技巧(Advanced Techniques)
1. 解包技巧:index, value
Unpacking: index, value
for i, val inenumerate(data):
# 直接使用 i 和 val
process(i, val)
2. 与 zip 结合
Combine with zip
names = [
'Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
for i, (name, score) inenumerate(zip(names, scores), start=1):
print(f"{i}. {name}: {score}分")
3. 在列表推导式中使用
In List Comprehensions
items = ['a', 'b', 'c']
result = [f"{i}:{x}"for i, x inenumerate(items)]
print(result) # ['0:a', '1:b', '2:c']
它是惰性求值的,节省内存。如需多次使用,可转换为列表:
t’s lazy-evaluated, memory-efficient. If you need multiple passes, convert it:
list (enumerate(items))
enumerate(items)[0] — it will raise an error. Convert to list first for random access.不要在循环中修改原列表
enumerateAvoid modifying the original list during iterationWhile enumerate won’t stop you, modifying the list can lead to logic errors or skipped elements.
It does more than just shorten code. It:
As stated in the Zen of Python:
而 for i, x in enumerate(...),正是这种美学的完美体现。
And is a perfect embodiment of that beauty.
下次当你想写 range(len(...)) 时,请记住:
Next time you reach for range(len(...)), remember:
“There’s a better way.”
那就是 enumerate。
That way is enumerate.
今天的分享就到这里了。如果您对文章有独特的想法,欢迎给我们留言,让我们相约明天。祝您今天过得开心快乐!That's all for today's sharing. If you have a unique idea about the article,please leave us a message,and let us meet tomorrow.I wish you a nice day!参考资料:通义千问 参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media. Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US. 本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通!LearningYard新学苑文字:song 排版:song 审核|qiu来源:泰耀教育