Exercise One:
# Compare two elements in the list, find the different elements and save in list 3L1 = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] L2 = ["Sun", "Mon", "Tue", "Tue", "Thu", "Sat"]
L3 = [] #先定义一个空列表 for i in L1: #遍历L1列表中的每一个元素 If I not in L2: #如果L1中的元素不在L2中 l3.append (i) #把元素写入L3中print(L3) #输出L3中的内容Exercise two:# Use the For statement to iterate through the contents of the following list:list = [1, 2, 3, 5, ' SD ', [1, ' se ', ' ds '], ' FS '
for i in list: #for direct traversal Print(i) #输出遍历的结果 Exercise Three:# Iterate through the list below and find the element with an odd indexlist = [ "Sun" " Mon ", " Tue " "Wed" , " Thu ", " Fri " "Sat" ] for i in range(1, len(list), 2): print(list[i]) Exercise 4:# already known list# namelist = [' stu1 ', ' stu2 ', ' stu3 ', ' stu4 ', ' stu5 ', ' stu6 ', ' stu7 ']# removelist = [' stu1 ', ' stu3 ', ' stu5 ', ' Stu6 ']# The same elements as the Removelist list will be removed in the NameList list
namelist = [' stu1 ', ' stu2 ', ' Stu3 ', ' Stu4 ', ' Stu5 ', ' Stu6 ', ' Stu7 '] removelist = [' stu1 ', ' Stu3 ', ' Stu5 ', ' Stu6 ']
for i in removelist: #直接遍历removelist列表中的元素 If i in NameList: #如果遍历出的结果存在namelist列表中, the element is removed from the NameList list Namelist.remove (i) #在namelist列表中删除该元素
print(namelist)
Python exercises--Traversal of the list