day5-列表相关练习题及解题答案

1.已知一个数字列表,求列表中心元素。

2.已知一个数字列表,求所有元素和。

3.已知一个数字列表,输出所有奇数下标元素。

4.已知一个数字列表,输出所有元素中,值为奇数的元素。

5.已知一个数字列表,将所有元素乘二。

例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]

# 1~5
nums = [1, 5, 88, 54, 12, 56, 43, 85, 3]
if len(nums) % 2 == 0:  # 数据时偶数个是,中心元素有两个
    center1, center2 = len(nums) // 2 - 1, len(nums) // 2
    print('中心元素是:', nums[center1], nums[center2])
else:
    center = len(nums) // 2
    print('中心元素是:', nums[center])
sums = 0
new_nums = []
print('奇数下标元素有:', end=' ')
for index, item in enumerate(nums):
    sums += item
    new_nums.append(item * 2)
    if index % 2 == 1:
        print(nums[index], end=' ')
print('所有元素之和为:', sums)
print('列表所有元素乘二后得到的新列表元素是:', new_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)
# 法二:运用集合的去重
names = ['石昊', '石毅', '石坚', '李白', '李白', '杜甫', '王维', '王维', '李商隐', '李清照']
print(set(names))

7.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)

scores = [1, 5, 88, 54, 12, 56, 43, 85, 3]
scores_max = max(scores)
scores_min = min(scores)
sums = 0
for score in scores:
    if score == scores_max or score == scores_min:
        continue
    sums += score
print(sums / (len(scores) - 2))

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 a in A:
    for b in B :
        if a == b:
            C.append(a)
print(C)

9.有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)

例如: nums = [19, 89, 90, 600, 1] —> 600

nums = [19, 89, 90, 600, 1]
Max = nums[0]
for num in nums[1:]:
    if Max < num:
        Max = num
print('最大值为', Max)

10.获取列表中出现次数最多的元素

例如:nums = [1, 2, 3,1,4,2,1,3,7,3,3] —> 打印:3

nums = [1, 1, 2, 3, 1, 4, 2, 1, 3, 7, 3, 3, 7, 7, 7]
new_nums = list(set(nums))  # [1,2,3,4, 7]
Max = nums.count(1)  # Max装的是最大计数
for new_num in new_nums[1:]:  # 这个循环是用来求得最大计数的
    if Max < nums.count(new_num):
        Max = nums.count(new_num) 
for new_num in new_nums:  # 此处在遍历一遍是否有多个最大计数等于Max的
    if nums.count(new_num) == Max:
        print(new_num)

11:用一个列表保存学生的分数,删除列表中所有低于60分的成绩

scores = [90, 45, 52, 10, 89, 67, 55, 32, 69, 100]
index = 0
while True:
    if scores[index] < 60:
        del scores[index]
        index -= 1  # 这儿加一是因为删掉这个元素后,下标也跟着修改了,得减一才能不漏掉遍历的元素
    index += 1
    if index >= len(scores):
        break
print(scores)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值