day5-列表作业

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

nums = [10, 20, 30, 40, 50]
if len(nums) % 2:
    print(nums[int(len(nums)/2)])
else:
    print(nums[int(len(nums)/2) - 1], nums[int(len(nums)/2)])

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

nums = [10, 20, 30, 40, 50]
s = 0
for x in nums:
    s += x
print(s)

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

nums = [10, 20, 30, 40, 50, 60, 70]
for index, item in enumerate(nums):
    if index % 2:
        print(item)

print(nums[1::2])

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

nums = [1, 2, 3, 4, 5, 6, 7]
for x in nums:
    if x % 2:
        print(x)

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

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

nums = [1, 2, 3, 4, 5, 6, 7]
for index, item in enumerate(nums):
    nums[index] = item * 2
print(nums)

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 = [90, 80, 100, 95, 85, 96, 82]
min_s = scores[0]
max_s= scores[0]
s = 0
count = 0
for x in scores:
    if x > max_s:
        max_s = x
    else:
        min_s = x
    s += x
average = (s - max_s - min_s) / (count - 2)
print(average)

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(x)
print(C)

for x in A:
	if x in B and 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_n = nums[0]
for x in nums:
    if x > max_n:
        max_n = x
print(max_n)

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]
nums_item = []
for x in nums:
    if x not in nums_item:
        nums_item.append(x)
print(nums_item)
max_count = 0
for x in nums_item:
    count = 0
    for y in nums:
        if x == y:
            count += 1
    print(count)

    if count > max_count:
        max_count = count
        max_count_num = x
else:
    print(max_count_num)

items = []
counts = []
for x in nums:
	if x not in items:
		items.append(x)
		counts.append(nums.count(x))
max_count = max(counts)
for index in range(len(counts)):
	if counts[index] == max_count
		print(items[index])
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值