day4作业和答案

本文介绍了Python中对数字列表的各种操作,包括计算列表中心元素、求元素和、提取奇数下标元素、筛选奇数值元素、元素乘二、去重、计算平均分、找出列表交集以及获取最大值。这些操作涵盖了基本的数据处理和列表操作技巧。
摘要由CSDN通过智能技术生成

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

list1 = [10, 206, 3, 89, 23, 9, 12]
count = len(list1)
if count & 1:
    print(list1[count//2])
else:
    print(list1[count//2-1], list1[count//2])

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

list1 = [1, 2, 3, 4, 5]
# 方法一:
sum1 = 0
for x in list1:
    sum1 += x
print(sum1)

# 方法二:
print(sum(list1))

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

list1 = [1, 2, 3, 4, 5, 6]

# 方法一:
for index in range(1, len(list1), 2):
    print(list1[index])

# 方法二:
print(list1[1::2])

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

list1 = [18, 25, 33, 40, 53, 6]
for x in list1:
    if x & 1:
        print(x)

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

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

# 方法一:
nums = [1, 2, 3, 4]
for index, item in enumerate(nums):
    nums[index] = item*2
print(nums)

# 方法二:
nums = [1, 2, 3, 4]
for index in range(len(nums)):
    nums[index] *= 2
print(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 = ['张三', '李四', '大黄', '张三', '张三', '张三', '李四', '隔壁老王']
for name in names[:]:
    if names.count(name) > 1:
        names.remove(name)
print(names)

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

scores = [13, 36, 78, 93, 99]
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, 2, 5, 10, 3, 2]
B = [5, 2, 10, 20, 32, 2]
C = []
for x in A:
    if x in B and x not in C:
        C.append(x)
print(C)    # [2, 5, 10]

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

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

scores = [13, 36, 78, 93, 99, 57]
max_score = scores[0]
for score in scores[1:]:
    if score > max_score:
        max_score = score
print(max_score)

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

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

nums = [1, 2, 3, 1, 4, 5, 3, 1, 4, 6, 7, 4]
max_count = 0
for x in nums:
    count = nums.count(x)
    if count > max_count:
        max_count = count

new_num = []
for x in nums:
    if nums.count(x) == max_count and x not in new_num:
        new_num.append(x)
print(new_num)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值