练习:取出列表内的偶数定义一个列表,内容是:[1,2,3,4,5,6,7,8,9,10] 遍历列表,取出列表内的偶数,并存入一个新的列表中。 使用for循环和while循环各做一次
一. 使用While循环解题
代码:
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = []
def new_list():
index = 0
while index < len(list1):
if list1[index] % 2 == 0:
list2.append(list1[index])
index += 1
return list2
print(new_list())
结果:
1. 定义题目中的列表和一个空列表
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = []
2.定义函数
def new_list():
3.定义下标索引为0
index = 0
4.当下标< 列表的长度
while index < len(list1):
5.判断列表中的值除于2的值是否有余数
if list1[index] % 2 == 0:
6.把list1中的元素添加到空列表中
list2.append(list1[index])
7.循环一次 index+1
index += 1
8.返回list2的值,并打印
return list2
print(new_list())
二. 接下来是For循环的做法:
代码:
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = []
def new_list1():
for i in list1:
if i % 2 == 0:
list2.append(i)
return list2
print(new_list1())
结合While循环做法步骤,很快就出答案
输出: