day5-列表作业_

本文介绍了Python编程中对数字列表的各种操作,包括查找列表中心元素、计算元素总和、筛选奇数下标元素、提取奇数值、元素乘二、去重、计算平均分以及找出列表交集等常见任务。这些技巧在数据处理和编程中非常实用。
摘要由CSDN通过智能技术生成

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

list1 = [10, 20, 40, 50, 60]
index = len(list1) // 2
if len(list1) % 2:
    print(list1[index])
else:
    print(list1[index - 1], list1[index]

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

sum1 = 0
list2 = [10, 23, 11, 45, 67]
for x in list2:
    sum1 += x
print(sum1)

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

#方法1
list3 = [10, 23, 11, 45, 67, 70]
for index in range(len(list3)):
    if index % 2:
        print(list3[index], end='\t')
#方法2
print(list3[1::2]) 

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

list4 = [10, 23, 11, 45, 67, 70, 22, 23]
for num in list3:
    if num % 2:
        print(num, end='\t')

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

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

#方法1
nums = [1, 2, 3, 4]
new_nums = []
for x in nums:
    new_nums.append(x * 2)
print(new_nums)
#方法2
nums = [1, 2, 3, 4]
index = 0
for x in nums:
    nums[index] = x * 2
    index += 1
print(nums)

6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的

例如:names = [‘张三’, ‘李四’, ‘大黄’, ‘大黄’, ‘张三’, ‘张三’, ‘张三’] -> names = [‘张三’, ‘李四’, ‘大黄’]

names = ['张三', '李四', '大黄', '大黄', '张三', '张三', '张三']
for index1 in range(len(names)-1, 0, -1):
    for name in names[index1-1::-1]:
        if names[index1] == name:
            names.remove(name)
            break
print(names)

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

scores = [100, 78, 90, 88, 93, 65, 60]
max_score = scores[0]
for score1 in scores[1:]:
    if score1 > max_score:
        max_score = score1
scores.remove(max_score)
min_score = scores[0]
for score2 in scores[1:]:
    if score2 < min_score:
        min_score = score2
scores.remove(min_score)
sum1 = 0
for score in scores:
    sum1 += score
print(sum1 // len(scores))

8.有两个列表A和B,使用列表C来获取两个列表中公共的元素

例如: A = [1, ‘a’, 4, 90] B = [‘a’, 8, ‘j’, 1] --> C = [1, ‘a’]

#当列表1和列表2都有重复元素的情况,则需要去重1
list1 = [1, 'a', 4, 90, 'a']
list2 = ['a', 8, 'j', 1, 'a']
new_list = []
for x in list1:
    for y in list2:
        if x == y:
            new_list.append(y)
for index1 in range(len(new_list)-1, 0, -1):
    for num in new_list[index1-1::-1]:
        if new_list[index1] == num:
            new_list.remove(num)
            break
print(new_list)

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

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

nums = [19, 89, 90, 600, 1]
max_num = nums[0]
for num in nums[1:]:
    if num > max_num:
        max_num = num
print(max_num)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值