2021.1.25-day5 列表作业

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

nums = [1,2,3,4,5]
media_nums = int((1+len(nums))/2)
print(nums[media_nums-1])   # 3

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

nums = [1,2,3,4,5]
sum = 0
for x in nums:
    sum += x
print(sum)     # 15

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

nums = [1,2,3,4,5]
for index in range(1,len(nums),2):
    print(index , nums[index])

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

nums = [1,2,3,4,5]
for x in nums:
    if x & 1:
        print(x)  # 1 3 5

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

nums = [1,2,3,4,5]
new_nums = []
for x in nums:
    element = x * 2
    new_nums.append(element)
print(new_nums)		# [2, 4, 6, 8, 10]

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

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

names = ['张三', '李四', '大黄', '大黄', '张三', '张三', '张三']
new_names = []
for x in names:
    if x not in new_names:
        new_names.append(x)
print(new_names)

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

scores = [7,8,9,10,9]
high= scores[0]
low = scores[0]
for x in scores:
    if high <= x:
        high = x
    if low >= x:
        low = x
scores.remove(high)
scores.remove(low)
sum = 0
for x in scores:
    sum += x
print(sum/len(scores))    # 8.666666666666666

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 x in A:
    for y in B:
        if x == y:
            C.append(y)
print(C)                       #  [1, 'a']

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

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

nums = [19, 89, 90, 600, 1]
max = nums[0]
for x in nums:
    if x >= max:
        max = x
print(max)

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]
new = []
new_count= []
for x in nums:
    if x not in new:
        new.append(x)
print(new)
for x in new:
    num = 0
    for y in nums:
        if x == y:
            num += 1
    new_count.append(num)
print(new_count)
max_index = new_count.index(max(new_count))
max = new[max_index]
print(max)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值