1.已知一个数字列表,求列表中心元素。
list1 = [1, 5, 7, 10, 9]
if len(list10) & 1:
print(list[len(list1) // 2])
else:
print(list1[len(list1) //2-1], list1[len(list1) // 2])
2.已知一个数字列表,求所有元素和。
# 方法一:
total = 0
list1 = [1, 5, 7, 10, 9]
for i in list1:
total += i
print(total)
# 方法二:
list1 = [1, 5, 7, 10, 9]
print(sum(list1))
3.已知一个数字列表,输出所有奇数下标元素。
# 方法一:
list1 = [1, 5, 7, 10, 9]
for i in range(1, len(list1), 2):
print(list1[i])
# 方法二:
print(list1[1::2])
4.已知一个数字列表,输出所有元素中,值为奇数的元素。
list1 = [1, 5, 7, 10, 9]
for num in list1:
if num & 1:
print(num)
5.已知一个数字列表,将所有元素乘二。
例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
# 方法一:
list1 = [1, 2, 3, 4]
for index, item in enumerate(list1):
list1[index] = item*2
print(list1)
# 方法二:
list1 = [1, 2, 3, 4]
for index in range(len(list1)):
list1[index] *= 2
print(list1)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = [‘张三’, ‘李四’, ‘大黄’, ‘张三’] -> names = [‘张三’, ‘李四’, ‘大黄’]
names = ['张三', '李四', '大黄', '张三', '张三', '李四', '大黄', '张三', '王五', '赵六']
print(list(set(names)))
# 方法一(利用新的列表,在新的列表中操作,空间换时间):
new = []
for name in names:
if name not in new:
new.append(name)
print(new)
# 方法二(不产生新列表,直接操作原列表):
names = ['张三', '李四', '大黄', '张三', '张三', '李四', '大黄', '张三', '王五', '赵六']
for name in names[:]:
if names.count(name) > 1:
names.remove(name)
print(names)
7.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
# 方法一:
total = 0
score = [88, 78, 99, 67, 70]
min_num = score[0]
max_num = score[-1]
for i in score:
if i < min_num:
min_num = i
if i > max_num:
max_num = i
score.remove(min_num)
score.remove(max_num)
for j in score:
total += j
print(total / len(score))
# 方法二:
score = [88, 78, 99, 67, 70]
score.remove(max(score))
score.remove(min(score))
print('最后得分:', sum(score)/len(score))
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 i in A:
if i in B and i not in C:
C.append(i)
print(C)
9.有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)
例如: nums = [19, 89, 90, 600, 1] —> 600
nums = [19, 89, 90, 600, 1]
max_num = nums[0]
for i in nums[1:]:
if i > max_num:
max_num = i
print(max_num)
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]
max_count = 0
for i in nums:
count = nums.count(i)
if count > max_count:
max_count = count
new_num = []
for i in nums:
if nums.count(i) == max_count and i not in new_num:
new_num.append(i)
print(new_num)
# 方法二:
nums = [1, 2, 3,1,4,2,1,3,7,3,3]
print(max(nums, key=nums.count))