1.已知一个数字列表,求列表中心元素。
nums = [1, 2, 3, 4]
# nums = [1, 2, 3]
nums_length = len(nums)
if nums_length % 2:
print(nums[nums_length // 2])
else:
print(nums[nums_length // 2 - 1], nums[nums_length // 2])
2.已知一个数字列表,求所有元素和。
nums = [1, 2, 3, 4]
print(sum(nums))
sum1 = 0
for i in nums:
sum1 += i
print(sum1)
3.已知一个数字列表,输出所有奇数下标元素。
nums = [1, 2, 3, 4]
nums_length = len(nums)
for i in range(1, nums_length, 2):
print(nums[i], end='\t')
print()
4.已知一个数字列表,输出所有元素中,值为奇数的元素。
nums = [1, 7, 3, 4, 6, 9]
for i in nums:
if i % 2:
print(i, end='\t')
print()
5.已知一个数字列表,将所有元素乘二。
例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
nums = [1, 7, 3, 4, 6, 9]
nums_length = len(nums)
for i in range(nums_length):
nums[i] *= 2
print(nums)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = [‘张三’, ‘李四’, ‘大黄’, ‘大黄’, ‘张三’, ‘张三’, ‘张三’] -> names = [‘张三’, ‘李四’, ‘大黄’]
names = ['张三', '李四', '大黄', '大黄', '张三', '张三', '张三', '赵六', '路人甲', '路人甲']
# 方法1:
print(list(set(names)))
# 方法2:
count = 0
while count < len(names) - 1:
if names[count] in names[count + 1:]:
del names[count]
else:
count += 1
print(names)
# 方法3:
names_nr = []
for i in names:
if i not in names_nr:
names_nr.append(i)
print(names_nr)
7.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
score = [78, 89, 95, 92, 66, 84, 75, 82, 88, 100]
# 方法1:
score.remove(max(score))
score.remove(min(score))
print(sum(score) / len(score))
# 方法2:
score = [78, 89, 95, 92, 66, 84, 75, 82, 88, 100]
max_num = 0
min_num = 100
sum_score = 0
for i in score:
if i > max_num:
max_num = i
if i < min_num:
min_num = i
sum_score += i
print((sum_score - max_num - min_num) / (len(score) - 2))
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:
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:
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]
# 方法1:
max_count_num = nums[-1]
max_count = nums.count(max_count_num)
while nums:
current_count = nums.count(nums[-1])
if current_count > max_count:
max_count_num = names[-1]
max_count = current_count
current_num = nums[-1]
for _ in range(current_count):
nums.remove(current_num)
print(max_count_num, max_count)