1. 基础题
-
已知一个数字列表,打印列表中所有的奇数
list1 = [1,2,3,4,5,6,7,8,9] for x in list1: if x % 2 == 1: print(x)
-
已知一个数字列表,打印列表中所有能被能被3整除但是不能被2整除的数
list2 = [1,2,3,4,5,6,7,8,9] for x in list2: if x % 3 == 0 and x % 2 != 0: print(x)
-
已知一个数字列表,计算所有偶数的和
list3 = [1,2,3,4,5,6,7,8,9] oushu = [] for x in list3: if x % 2 == 0: oushu.append(x) print(sum(oushu))
-
已知一个数字列表,统计列表中十位数是
1
的数的个数list4 = [11,32,13,54,15,56,517,218,119] shi1 = [] for x in list4: if x % 100 // 10 == 1: shi1.append(x) print(shi1)
-
已知一个列表,获取列表中下标为奇数是所有元素(从0开始的下标值)
例如: list1 = [10, 20, 5, 34, 90, 8]
结果:[20, 34, 8]
list1 = [10, 20, 5, 34, 90, 8] jishu = [] for x in range(len(list1)): if x % 2 == 1: jishu.append(list1[x]) print(jishu)
-
已知一个数字列表,将列表中所有元素乘以2
例如: nums = [10, 3, 6, 12] 乘2后: nums = [20, 6, 12, 24]
nums = [10, 3, 6, 12] new_nums=[] for s in nums: new_nums.append(s * 2) nums = new_nums print(nums)
-
已知一个列表,获取列表的中心元素
例如:nums = [10, 2, 6, 12] -> 中心元素为: 2和6
nums = [10, 2, 6, 12, 10] -> 中心元素为:6
nums = [10, 2, 6, 12, 10] length = len(nums) print(length) if length % 2 == 0: print('中心元素为:',nums[length // 2 - 1],'和',nums[length // 2]) else: print('中心元素为:',nums[length // 2])
2. 进阶题
-
定义一个列表保存多个学生的分数,删除列表中所以低于60分的值
例如: scores = [45, 60, 89, 30, 12, 59, 99, 80, 71, 66] 删除后: scores = [60, 89, 99, 80, 71, 66]
scores = [45, 60, 89, 30, 12, 59, 99, 80, 71, 66] new_scores = [] for index in range(len(scores)): s = scores[index] if s >= 60: new_scores.append(s) scores = new_scores print(scores)
-
已知一个列表保存了多个学生的姓名,要求去掉列表中重复的名字
例如:names = [‘小明’, ‘张三’, ‘李四’, ‘张三’, ‘张三’, ‘小明’, ‘王五’, ‘王五’]
去重后:names = [‘小明’, ‘张三’, ‘李四’, ‘王五’]
names = ['小明', '张三', '李四', '张三', '张三', '小明', '王五', '王五'] new_names = [] for s in names: if s not in new_names: new_names.append(s) names = new_names print(names)
-
已知一个数字列表,获取列表中值最大的元素 (不能使用max函数)
nums = [134, 289, 398, 345, 786, 723, 1236] max1 = nums[0] for s in nums: if max1 < s: max1 = s print(max1)
4.已知两个有序列表(列表中的元素已经按照从小到大的方式排好序),要求合并两个列表,合并后元素还是从小到大排序
例如: list1 = [10, 23, 39, 41, 52, 55, 80] list2 = [9, 38, 55, 70]
合并后的结果: [9, 10, 23, 38, 39, 41, 52, 55, 55, 70, 80]
list1 = [10,23,39,41,52,55,80]
list2 = [9,38,55,70]
new_list = sorted(list1 + list2)
print(new_list)
5.已知一个有序数字列表(从小到大),输入任意一个数字,将输入的数字插入列表中,要求插入后列表仍然保持从小到大排序的关系
例如: list1 = [10, 23, 45, 67, 91] 输入: 50 -> list1 = [10, 23, 45, 50, 67, 91]
list1 = [10, 23, 45, 67, 91]
x = int(input('请输入一个数:'))
list1.append(x)
list1=sorted(list1)
print(list1)