# 方法1:
list1 =[98,94,88,87,85,73,70,52,-54,-59]print([x for x in list1 if x %2!=0])# [87, 85, 73, -59]# 方法2:--- 有问题的代码!!!for x in list1:if x %2==0:
list1.remove(x)print(list1)# [94, 87, 85, 73, 52, -59]# 第1次循环取列表中的第1个元素:# x = 98 -> if 98 % 2 == 0 -> if True -> list1.remove(98) -> list1 = [94, 88, 87, 85, 73, 70, 52, -54, -59]# 第2次循环取列表中的第2个元素:# x = 88 -> if 88 % 2 == 0 -> if True -> list1.remove(88) -> list1 = [94, 87, 85, 73, 70, 52, -54, -59]# 第3次循环取列表中的第3个元素:# x = 85 -> if 88 % 2 == 0 -> if False -> list1 = [94, 87, 85, 73, 70, 52, -54, -59]# 依次类推会发现列表的循环移除元素有些时候会移除不干净。# 解决方案1:复制一个一模一样的列表根据新列表的内容去删除旧列表
list1 =[98,94,88,87,85,73,70,52,-54,-59]
list2 = list1.copy()for x in list2:if x %2==0:
list1.remove(x)print(list1)# [87, 85, 73, -59]# 解决方案2:倒过来遍历去删除,就不会影响遍历的元素位置,for index inrange(len(list1)-1,-1,-1):if list1[index]%2==0:del list1[index]print(list1)# [87, 85, 73, -59]# 解决方案3:根据列表的下标去删除元素
list1 =[98,94,88,87,85,73,70,52,-54,-59]
index =0whileTrue:if list1[index]%2==0:del list1[index]else:
index +=1if index >=len(list1):breakprint(list1)# [87, 85, 73, -59]
6.编写一个程序,创建一个包含10个随机整数的列表,并将列表中的元素去重。
# 方法1
list1 =[98,52,88,87,88,73,70,52,98,88]print(list(set(list1)))# [98, 70, 73, 52, 87, 88]# 方法2
new_list =[]for x in list1:if x notin new_list:
new_list.append(x)print(new_list)# [98, 52, 88, 87, 73, 70]
7.编写一个程序,创建一个包含10个随机整数的列表,并计算列表中大于等于5的元素的个数。
nums =[23,9,89,23,2,12,9,2,3,39]# 方法1:
count =0for x in nums:if x >=5:
count +=1print(count)# 方法2:print(len([x for x in nums if x >=5]))
8.编写一个程序,创建一个包含10个随机整数的列表,并统计列表中每个元素出现的次数。
nums =[10,20,20,33,33,33,45,54,54,99]# 去重
new_nums =[]for x in nums:if x notin new_nums:
new_nums.append(x)# 统计个数for x in new_nums:print(nums.count(x),'个', x, sep='')
9.编写一个程序,创建一个包含10个随机整数的列表,并找出列表中的第一个负数。
num1 =[10,5,3,-1,5,1,20,-3,-2,0]for i in num1:if i <0:print(i)break