1.已知一个数字列表,求列表中心元素。
list1 = [0, 57, 24, 68, 42, 77, 99, 104, 245]
if len(list1) % 2:
print('列表的中心元素是:', list1[len(list1) // 2])
else:
print('列表中的中心元素是:', list1[len(list1) // 2 - 1], '和', list1[len(list1) // 2])
2.已知一个数字列表,求所有元素和。
list1 = [1, 20, 50, 80, 100, 600]
sum1 = 0
for x in list1:
sum1 += x
print(sum1)
3.已知一个数字列表,输出所有奇数下标元素。
# 方法一:
list1 = [0, 57, 24, 68, 42, 77, 99, 104, 245]
for index in range(len(list1)):
if list1[index] % 2:
print(list1[index], '的下标元素是:', index, sep='')
# 方法二:
print(list1[1::2])
4.已知一个数字列表,输出所有元素中,值为奇数的元素。
list1 = [0, 57, 24, 68, 42, 77, 99, 104, 245]
for x in list1:
if x % 2:
print(x, sep='', end=' ')
print()
5.已知一个数字列表,将所有元素乘二。
例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
# 方法一:
list1 = [1, 2, 3, 4, 5, 6]
list2 = []
for x in list1:
list2.append(x * 2)
print(list2)
# 方法二:
list1 = [1, 2, 3, 4, 5, 6]
for index in range(len(list1)):
list1[index] *= 2
print(list1)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = [‘张三’, ‘李四’, ‘大黄’, ‘大黄’, ‘张三’, ‘张三’, ‘张三’] -> names = [‘张三’, ‘李四’, ‘大黄’]
names = ['张三', '李四', '大黄', '大黄', '张三', '张三', '张三', '王二', '王二', '李四']
new_names = []
for x in names:
if x not in new_names:
new_names.append(x)
print(new_names)
7.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
# 方法一:
scores = [28, 55, 69, 78, 89, 90, 98, 100]
min_score = scores[0]
max_score = scores[0]
scores2 = []
new_scores = []
for score in scores:
if score > max_score:
max_score = score
elif score < min_score:
min_score = score
scores2.append(max_score)
scores2.append(min_score)
for new_score in scores:
if new_score not in scores2:
new_scores.append(new_score)
average = sum(new_scores)/len(new_scores)
print('平均分是:', average)
# 方法二:
scores = [28, 55, 69, 78, 89, 90, 98, 100]
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, 1, 1, 1, 1]
B = ['a', 8, 'j', 1]
C = []
for x in A:
if x in B:
if x not in C:
C.append(x)
print(C)
9.有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)
例如: nums = [19, 89, 90, 600, 1] —> 600
nums = [19, 89, 90, 600, 1]
max_num = nums[0]
for num in nums:
if num > max_num:
max_num = num
print(max_num)
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]
num, count = 0, 0
for x in nums:
if nums.count(x) > count:
num = x
count = nums.count(x)
print(num)
# 方法二:
nums = [1, 2, 3, 1, 4, 2, 1, 3, 7, 3, 3]
count1 = 0
count_max = 0
for x in range(0, len(nums)):
count2 = 1
for y in range(x + 1, len(nums)):
if nums[x] == nums[y]:
count2 += 1
if count2 > count1:
count1 = count2
count_max = x
print(nums[count_max])