1.已知一个数字列表,求列表中心元素。
nums = [10, 20, 30, 50, 450]
n = len(nums) # 统计nums的长度
if n % 2 == 0: #判断n为奇数还是偶数
print(nums[n//2], nums[n//2-1]) # 是偶数则输出下标在中间的两位数字
else:
print(nums[(n+1)//2-1]) # 是奇数则输出下标在中间数字
2.已知一个数字列表,求所有元素和。
nums = [10, 20, 30, 50, 450]
sum1 = 0
for item in nums: # 依次取出nums中的数字
sum1 += item # 求和
print(sum1)
3.已知一个数字列表,输出所有奇数下标元素。
nums = [10, 20, 30, 50, 450]
for index in range(len(nums)): # 取出nums中的下标
if index % 2 == 0: # 判断下标为奇数还是偶数
continue # 结束本次循环,进入下一次循环
else:
print(nums[index])
4.已知一个数字列表,输出所有元素中,值为奇数的元素。
nums = [10, 20, 30, 50, 450, 1]
for item in nums: # 依次取出nums中的元素
if item % 2 != 0: # 判断元素为奇数还是偶数
print(item)
5.已知一个数字列表,将所有元素乘二。
例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
nums = [10, 20, 30, 50, 450, 1]
for index in range(len(nums)): # 依次取出nums中的所有下标
nums[index] *= 2 # 将所有元素乘以二
print(nums)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = [‘张三’, ‘李四’, ‘大黄’, ‘大黄’, ‘张三’, ‘张三’, ‘张三’] -> names = [‘张三’, ‘李四’, ‘大黄’]
names = ['hello', 'chat', 'baby', 'maybe', 'hello', 'baby', 'hello', 'chat', 'maybe', 'hello']
for item in names: # 依次取出names中的元素
if names.count(item) >= 2: # 判断元素是否重复
names.remove(item) # 删除重复元素
print(names)
7.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
scores = [90, 45, 56, 89, 76, 56, 92, 45, 30, 59, 67, 70]
scores.remove(max(scores)) # 去掉最大值
scores.remove(min(scores)) # 去点最小值
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 item in A: # 依次取出A中的元素
if item in B: # 判断元素是否在B中出现
C.append(item) # 向C中添加共有元素
print(C)
9.有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)
例如: nums = [19, 89, 90, 600, 1] —> 600
nums = [19, 89, 90, 600, 1]
a = 0
for item in nums: # 依次取出nums中的元素
if item >= a: # 判断元素是否比a大
a = item # 如果比a大,就赋值给a
print(a)
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]
a = 0
b = 0
for item in nums: # 依次取出nums中的元素
if nums.count(item) > a: # 判断元素在nums中的出现次数是否比a大
a = nums.count(item) # 将出现次数比a大的次数赋值给a
b = item # 将元素值赋值给b
print(b)