本文共 2649 字,大约阅读时间需要 8 分钟。
列表元素的增删改
del 列表[下标] - 删除列表中指定下标对应的元素
注意:下标不能越界列表.remove(元素) - 删除列表中指定元素
如果需要删除的元素在列表中有多个,只删最前面哪一个
如果需要删除的元素不存在,程序会报错
列表.pop() - 取出列表最后一个元素,并且返回
列表.pop(下标) - 取出列表中指定下标对应的元素,并且返回
补充:如果直接用一个列表变量给另外一个变量赋值,赋的是原变量中数据的地址
列表1 + 列表2 - 将两个列表合并产生一个新的列表
列表 * N - 列表中的元素重复N次产生一个新的列表元素 in 列表 - 判断指定元素是否在指定列表中
元素 not in 列表 - 判断指定元素是否不在指定列表中1.已知一个数字列表,求列表中心元素。
nums = (10,23,45,12,67,89,76,53,35,23,56,79,9,90,25,30,40)x = len(nums)if x % 2 == 0: print('列表中心元素:',nums[x // 2])else: print('列表中心元素:',nums[x // 2-1],nums[x // 2])
2.已知一个数字列表,求所有元素和。
nums = (10,23,45,12,67,89,76,53,35,23,56,79,9,90,25,30,40)sum=0for num in nums: sum += numprint('所有元素和:',sum)
3.已知一个数字列表,输出所有奇数下标元素。
nums = (10,23,45,67,89,76,53,35,56,79,9,90,25,40)for index in range(len(nums)): if index % 2 == 1: print(nums[index],end=' ')
4.已知一个数字列表,输出所有元素中,值为奇数的元素。
nums = (10,23,45,67,89,76,53,35,56,79,9,90,25,40)for num in nums: if num % 2 == 1: print(num,end=' ')
5.已知一个数字列表,将所有元素乘二。
例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
nums = (10,23,45,67,89,76,53,35,56,79,9,90,25,40)for index in range(len(nums)): nums[index] *= 2print(nums)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = [‘张三’, ‘李四’, ‘大黄’, ‘大黄’, ‘张三’, ‘张三’, ‘张三’] -> names = [‘张三’, ‘李四’, ‘大黄’]
names = ['张三','李四', '大黄', '大黄','张三','张三','张三']new_names=[]for name in names: if name not in new_names: new_names.append(name)print(new_names)
7.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
scores = (23,45,67,89,76,35,56,79,90,80,40)max_score = scores[0]min_score = scores[0]for x in scores: if x > max_score: max_score = x if x < min_score: min_score = xscores.remove(max_score)scores.remove(min_score)print('平均分数:', sum(scores) / len(scores))
8.有两个列表A和B,使用列表C来获取两个列表中公共的元素
例如: A = [1, ‘a’, 4, 90] B = [‘a’, 8, ‘j’, 1] --> C = [1, ‘a’]
A = [1, 'a', 4, 90]B = ['a', 8, 'j', 1]C = []for x in A: for y in B: if x == y: C.append(x)print(C)
9.*有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)
例如: nums = [19, 89, 90, 600, 1] —> 600
nums = [19, 89, 90, 600, 1]max_nums = 0for x in nums: if x >max_nums: max_nums = xprint(max_nums)
10.*获取列表中出现次数最多的元素
例如:nums = [1, 2, 3,1,4,2,1,3,7,3,3] —> 打印:3
nums = [1, 2, 3,1,4,2,1,3,7,3,3]new_nums = []count = 0for x in nums: if x not in new_nums: new_nums.append(x)for y in new_nums: count1 = 0 for x in nums: if y == x: count1 += 1 if count1 > count: count = count1 more = x else: passprint(more)
转载地址:http://jxuhf.baihongyu.com/