1.已知一个数字列表,求列表中心元素。
list1 = list(input('请输入列表的元素:'))
if len(list1) % 2 != 0:
print('你输入的列表为:', list1, '-->其中心元素为:', list1[len(list1) // 2])
else:
print('你输入的列表为:', list1, '-->其中心元素为:', list1[len(list1) // 2-1:len(list1)//2+1])
2.已知一个数字列表,求所有元素和。
list2 = [1, 2, 3, 4, 5]
result = 0
for num in list2:
result += num
print('列表', list2, '中各元素相加的和为%d' % result)
3.已知一个数字列表,输出所有奇数下标元素。
list3 = [1, 2, 3, 4, 5]
print('列表', list3, '下标为奇数位上的数字为', list3[1::2])
4.已知一个数字列表,输出所有元素中,值为奇数的。
list4 = [1, 2, 3, 4, 5]
print('列表', list4, '中值为奇数的数字有:')
for num in list4:
if num % 2 ==1:
print(num)
5.已知一个数字列表,将所有元素乘二。
例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
nums = [1, 2, 3, 4]
new_nums = []
for items in nums:
items *= 2
new_nums.append(items)
print(new_nums)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = ['张三', '李四', '大黄', '张三'] -> names = ['张三', '李四', '大黄']
names = ['张三', '李四', '大黄', '张三', '张三', '李四', '大黄', '张三', '阿狗', '阿猫']
names2 = []
for i in range(len(names)):
if names[i] not in names2:
names2.append(names[i])
print(names2)
7.已经一个数字列表(数字大小在0~6535之间), 将列表转换成数字对应的字符列表
例如: list1 = [97, 98, 99] -> list1 = ['a', 'b', 'c']
list7 = [97, 98, 99]
new_list7 = []
for items in list7:
items = chr(items)
new_list7.append(items)
print(new_list7)
8.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
score = [89, 95, 76, 94, 83, 70, 77]
score.remove(max(score)) # 去掉最大值
score.remove(min(score)) # 去掉最小值
total_score = 0
for items in score:
total_score += items
print('去掉最高分和最低分后平均值为:', total_score/len(score), '分')
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 x in A:
for y in B:
if x == y:
C.append(x)
print(C)
10.有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)
例如: nums = [19, 89, 90, 600, 1] —> 600
nums1 = [19, 89, 90, 600, 1]
max_nums1 = nums1[0]
for x in nums1:
if x > max_nums1:
max_nums1 = x
print(max_nums1)
11.获取列表中出现次数最多的元素
例如:nums = [1, 2, 3,1,4,2,1,3,7,3,3] —> 打印:3