day7-作业

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

num_str = input("请输入一列数字,用空格隔开:")
num_list = num_str.split()
lenth = len(num_list)
if lenth%2 == 0:
    print("中心元素为:{}和{}".format(num_list[lenth//2-1],num_list[lenth//2]))
else:
    print("中心元素为:{}".format(num_list[(lenth-1)//2]))

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

num_list = [1, 2, 3, 4, 5]
sum_list = sum(num_list)
print("和:",sum_list)

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

num_list = [1, 2, 3, 4, 5, 6]
index = 1
while index <len(num_list):
    print(num_list[index], end = ' ')
    index += 2

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

num_list = [1, 2, 3, 4, 5, 6, 7, 8]
for item in num_list:
    if item%2 != 0:
        print(item, end = ' ')

5.已知一个数字列表,将所有元素乘二。
例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]

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

6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = ['张三', '李四', '大黄', '张三'] -> names = ['张三', '李四', '大黄']

names = ['张三', '李四', '大黄', '张三']
names.reverse()
for item in names[:]:
    if names.count(item) > 1:
        names.remove(item)
names.reverse()
print(names)

7.已知一个数字列表(数字大小在0~6535之间), 将列表转换成数字对应的字符列表
例如: list1 = [97, 98, 99] -> list1 = ['a', 'b', 'c']

list1 = [97, 98, 99]
for index in range(len(list1)):
    list1[index] = chr(list1[index])
print(list1)

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

scores = [1, 2, 3, 4, 5, 6, 7, 8, 9]
scores.remove(max(scores))
scores.remove(min(scores))
sum = 0
for item in scores:
    sum += item
print("平均分为:", sum/len(scores))

9.有两个列表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 item_A in A:
    if item_A in item_B and item_A not in C:
        C.append(item_A)
print(C)

10.有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)
例如: nums = [19, 89, 90, 600, 1] —> 600

nums = [19, 89, 90, 600, 1]
nums.sort()
print(nums[-1])

11.获取列表中出现次数最多的元素
例如: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]
max_count = 0
for item in nums:
    if nums.count(item) > max_count:
        max_count = nums.count(item)
new_nums = []
for item in nums:
    if nums.count(item) == max_count:
        if item not in new_nums:
            new_nums.append(item)
for item in new_nums:
    print(item , end = ' ')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。