Python3下的【并行迭代】与【按索引

发布时间:2019-09-26 07:27:17编辑:auto阅读(1819)

    在使用python3时,有【并行迭代】与【按索引迭代】,并行迭代相对来说好理解,现在介绍下【按索引迭代】。

    废话不多,直接上实例

    # Demo:并行迭代 zip函数

    names = ["anne","beth","george","damon","bob"]

    ages = [12,45,32,102,101,103]

    # names 与 ages 列表元素可以不等同,按数量少的进行对应

    for name,age in zip(names,ages):

         print(name,"is",age,"years old!")





    按索引迭代案例

    按索引迭代方式一

    strings = ["Alice","Bob","Nick"]

    # strings[1] = "leo" #测试给列表添加元素后,的效果

    # print(strings)

    index = 0

    for string in strings:

        if "ob" in string:

            strings[index] = "Tom" # 将含有“ob”的元素,替换为Tom

        index += 1

    print(strings)


    按索引迭代方式二

    strings = ["Alice","Bob","Nick"]

    index = 0

    for index,string in enumerate(strings): 

        if "ob" in string:

            strings[index] = "Tom"

    print(strings)


关键字