全部文章

遍历技巧(各种数据的for循环技巧)

字典中遍历时,关键字和对应的值可以使用 items() 方法同时解读出来:

dictTest={"name":"jack","age":18,"sex":"male"}
print(dictTest)
for k,v in dictTest.items():
    print(k,v)

序列中遍历时,索引位置和对应值可以使用 enumerate() 函数同时得到:

listTest=["one","two","three"]
for i,v in enumerate(listTest):
    print(i,v)

同时遍历两个或更多的序列,可以使用 zip() 组合:

list1 = ["one", "two", "three"]
list2 = [1, 2, 3, 4, 5]

for l1, l2 in zip(list1, list2):
    print(" {1} 的英语是 {0} ".format(l1, l2))

    # 打印内容:
    """
 1 的英语是 one 
 2 的英语是 two 
 3 的英语是 three 
    """

反向遍历一个序列,首先指定这个序列,然后调用 reversed() 函数:

list1 = ["one", "two", "three"]
for i in reversed(list1):
    print(i, end=" ")#three two one 

要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值:

list1 = ["one", "two", "three"]
for i in sorted(list1):
    print(i, end=" ")#one three two 

 

posted @ 2025-03-12 12:29  指尖下的世界  阅读(3)  评论(0)    收藏  举报