Python第六章06:列表的循环练习

复制代码
# 遍历列表课后题
"""
定义一个列表,内容是:[1,2,3,4,5,6,7,8,9,10]
1.遍历列表,取出列表内的偶数,并存入一个新的列表对象中
2.使用while循环和for循环各操作一次
提示:
1.通过if判断来确认偶数:  if x %2 == 0
2.通过列表的appdend方法,来增加元素
"""

# while 循环遍历
my_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
my_list2 = []
a = 0
while a < len(my_list):
    element = my_list[a]
    if element %2 == 0:
        my_list2.append(element)
    a += 1
print(f"while循环取出偶数后,得到新的列表是:{my_list2}")
# for 循环遍历
list_1 = [21,22,23,24,25,26,27,28,29,30,40,45,66,86]
list_2 = []
for x in list_1:
    if x %2 == 0:
        list_2.append(x)
print(f"for循环取出偶数,形成新列表是:{list_2}")

运行结果:

相关推荐
许彰午4 小时前
74_Python自动化办公之Excel操作
python·自动化·excel
用户8356290780511 天前
Python 实现 PDF 文件加密与解密方法
后端·python
用户8356290780511 天前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生1 天前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师1 天前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码1 天前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf1 天前
FastAPI 如何连接 MySQL
后端·python
apocelipes2 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780512 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent2 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python