Files
Python_CookBook_repo/4.迭代器与生成器/10.以键值对的方式迭代索引.py
2025-09-10 16:12:45 +08:00

14 lines
563 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

if __name__ == "__main__":
my_list = [1,2,3,4,5,6,7,8,9]
# 有时候,我们想要在迭代的时候知道元素的下标,有些傻子(比如我)就很傻逼的做了个计数器
# 但是其实直接使用enumerate就行
for index, number in enumerate(my_list, start=0):
print(index, number)
# 但是如果可迭代对象的子元素是元组,那请务必别把元组的标识拆开
my_list = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
for index, (x, y) in enumerate(my_list, start=1):
print(index, x, y)