Python:列表的循环遍历

  • while循环遍历
  • for循环遍历
# 列表的遍历 - while循环遍历
def list_while_func():
    """
    列表的遍历 - while循环遍历
    :return: None
    """
    list1 = [21, 25, 21, 23, 22, 20]
    index = 0
    while index < len(list1):
        tmp = list1[index]
        index += 1
        print(index)


# 列表的遍历 - for循环遍历
def list_for_func():
    """
    列表的遍历 - for循环遍历
    :return: None
    """
    mylist = ["itheima", "itcast", "python", "itheima", "itcast", "python"]

    for i in mylist:
        print(i)


list_while_func()
list_for_func()

# 练习:取出列表内的偶数
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 使用while循环遍历出偶数
def list_while_two(mylist):
    """
    使用while循环遍历出偶数
    :param mylist: 需要取偶数的列表
    :return: None
    """
    index = 0
    tmp_list = []
    while index < len(mylist):

        if mylist[index] % 2 == 0:
            tmp_list.append(mylist[index])
        index += 1

    print(tmp_list)
# 使用for循环遍历出偶数
def list_for_two(mylist):
    """
    使用for循环遍历出偶数
    :param mylist: 需要取偶数的列表
    :return: None
    """
    tmp_list = []
    for i in mylist:
        if i % 2 == 0:
            tmp_list.append(i)

    print(tmp_list)




list_while_two(mylist)
list_for_two(mylist)
posted @ 2023-12-08 23:49  hugh2023  阅读(187)  评论(0)    收藏  举报