1.已知一个数字列表,求列表中心元素。
num = [1, 2, 3, 4, 65, 66]
index = len(num) // 2
print((num[index] - 1), num[index])
2.已知一个数字列表,求所有元素和。
num = [1, 2, 3, 4, 65, 66]
sum1 = 0
for index in range(len(num)):
sum1 += num[index]
print(sum1)
3.已知一个数字列表,输出所有奇数下标元素。
num = [1, 2, 3, 4, 65, 66]
for index in range(1, len(num), 2):
print(num[index])
4.已知一个数字列表,输出所有元素中,值为奇数的元素。
num = [1, 2, 3, 4, 65, 66]
for index in range(len(num)):
if num[index] & 1 == 1:
print(num[index])
5.已知一个数字列表,将所有元素乘二。
例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
num = [1, 2, 3, 4, 65, 66]
for index in range(len(num)):
num[index] = num[index] * 2
print(num)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = [‘张三’, ‘李四’, ‘大黄’, ‘大黄’, ‘张三’, ‘张三’, ‘张三’] -> names = [‘张三’, ‘李四’, ‘大黄’]
name1 = ['张三', '李四', '大黄', '大黄', '张三', '张三', '张三']
name2 = ['张三', '李四', '大黄', '大黄', '张三', '张三', '张三']
count = 0
for i in name1:
count = 0
for j in name2:
if i == j:
count += 1
if count > 1:
for k in range(count - 1):
name2.remove(i)
print(name2)
7.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
scores = list(map(int, input('请输入分数:').split(' ')))
max = scores[0]
min = scores[0]
sum1 = 0
for i in range(len(scores)):
if scores[i] >= max:
max = scores[i]
for j in range(len(scores)):
if scores[j] <= min:
min = scores[j]
scores.remove(max)
scores.remove(min)
for k in scores:
sum1 += k
print(sum1 / 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 i in A:
for j in B:
if i == j:
C.append(i)
print(C)
9.*有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)
例如: nums = [19, 89, 90, 600, 1] —> 600
nums = [19, 89, 90, 600, 1]
max = nums[0]
for i in nums:
if i >= max:
max = i
print(max)
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]
count1 = 0
count2 = 0
k = 0
for i in nums:
count1 = 0
for j in nums:
if i == j:
count1 += 1
if count1 > count2:
count2 = count1
k = i
print(i)