1.已知一个数字列表,求列表中心元素。
nums = [1, 2, 3, 4, 5, 6]
n = len(nums)
if n % 2 != 0:
print(nums[n//2])
else:
print(nums[n//2-1], nums[n//2])
2.已知一个数字列表,求所有元素和。
nums = [1, 2, 3, 4, 5, 6] # 方法一
print(sum(nums))
sum1 = 0
for item in nums:
sum1 += item # 方法二
print(sum1)
3.已知一个数字列表,输出所有奇数下标元素。
nums = [1, 2, 3, 3, 4, 5, 6, 4, 6]
n = len(nums) # 9
for index in range(1, n, 2):
print(nums[index], end=' ')
4.已知一个数字列表,输出所有元素中,值为奇数的元素。
nums = [1, 2, 3, 3, 4, 5, 5, 11, 7, 6, 4, 6]
for item in nums:
if item % 2 != 0:
print(item, end=' ')
5.已知一个数字列表,将所有元素乘二。例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
nums = [1, 2, 3, 4, 5]
for index in range(len(nums)):
nums[index] *= 2
print(nums)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的。例如:names = ['张三', '李四', '大黄', '张三'] -> names = ['张三', '李四', '大黄']
names = ['张三', '李白', '大黄', '张三', '李四', 'MJ', 'AI', '李世民', '李四', '徐3']
for item in names[:]:
if names.count(item) > 1:
names.remove(item)
print(names)
7.已经一个数字列表(数字大小在0~6535之间), 将列表转换成数字对应的字符列表。例如: list1 = [97, 98, 99] -> list1 = ['a', 'b', 'c']
list1 = [97, 98, 99, 103, 1003]
for index in range(len(list1)):
list1[index] = chr(list1[index])
print(list1)
8.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
scores = [90, 90, 80, 70, 30, 60, 50, 30]
max1 = max(scores)
min1 = min(scores)
for item in scores[:]:
if item == max1:
scores.remove(item)
max1 += 1
if item == min1:
scores.remove(item)
min1 -= 1
print(scores)
avg = sum(scores) / len(scores)
print(avg)
scores = [90, 90, 80, 70, 30, 60, 50, 30]
scores.sort()
avg = sum(scores[1:-1]) / (len(scores)-2)
print('平均分:%.1f' % avg)
9.有两个列表A和B,使用列表C来获取两个列表中公共的元素。例如: A = [1, 'a', 4, 90] B = ['a', 8, 'j', 1] --> C = [1, 'a']
list1 = [1, 'a', 4, 90, 1]
list2 = ['a', 8, 'j', 1, 1]
list3 = []
for item in list1:
if item in list2:
list3.append(item)
for item in list3[:]:
if list3.count(item) > 1:
list3.remove(item)
print(list3)
A = [1, 'a', 4, 90, 1]
B = ['a', 8, 'j', 1, 1]
C = []
for item in A:
if (item in B) and (item not in C):
C.append(item)
print(C)
10.有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)。例如: nums = [19, 89, 90, 600, 1] —> 600
nums = [-19, -89, -90, -600, -600, -350, -1]
max1 = nums[0]
for item in nums[1:]:
if item > max1:
max1 = item
print(max1)
11.获取列表中出现次数最多的元素。例如:nums = [1, 2, 3,1,4,2,1,3,7,3,3] —> 打印:3
nums = [9, 7, 1, 7, 2, 3,1,4,2,1,3,7,3,3, 7]
max1 = 0
for item in nums:
if nums.count(item) > max1:
max1 = nums.count(item)
new_nums = []
for item in nums:
if nums.count(item) == max1:
if item not in new_nums:
new_nums.append(item)
print(new_nums)