Python入门--列表遍历

1、打开Pycharm,创建Python文件,复制代码,保存运行!
在这里插入图片描述

"""
Time : 2024/1/16 14:18
Author : XFL
"""

def list_while_func():
    """
    # 1、使用while遍历列表
    :return: None
    """
    mylist = ["xppp","xpp","acb","hello","xpp","pycharm","java","xpp"]
    index = 0
    while index < len(mylist):
        print(f"使用while遍历列表:{mylist[index]}")
        index += 1
    print(f"while循环执行{index}次")

def list_for_func():
    """
    # 2、使用for遍历列表
    :return: None
    """
    mylist = ["xppp", "xpp", "acb", "hello", "xpp", "pycharm", "java", "xpp"]
    index = 0
    for index in range(0,len(mylist)):
        print(f"使用for循环遍历列表:{mylist[index]}")
        index += 1
    print(f"for循环执行{index}次")

# 函数的调用
list_while_func()
list_for_func()

# 定义一个列表,内容是:[1,2,3,4,5,6,7,8,9,10]
# 遍历列表,取出列表内的偶数,并存入一个新的列表对象中
# 使用while循环和for循环各操作一次



def list_while_double():
    """
    使用while输出偶数,并插入新的列表中
    :return: None
    """
    mylist1 = [1,2,3,4,5,6,7,8,9,10]
    list_double = []
    index = 0
    while index < len(mylist1):
        if mylist1[index] % 2 == 0:
            list_double.append(mylist1[index])
        index += 1
    print(f"使用while输出偶数的结果{list_double}")

def list_for_double():
    """
    使用for输出偶数,并插入新的列表中
    :return: None
    """
    mylist1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    list_double = []
    index = 0
    for index in range(0,len(mylist1)):
        if mylist1[index] % 2 == 0:
            list_double.append(mylist1[index])
        index += 1
    print(f"使用for输出偶数的结果{list_double}")

# 函数的调用
list_while_double()
list_for_double()
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值