1.已知一个数字列表,求列表中心元素。
scores =[34, 56, 23,12,78, 90, 24, 35, 46, 58, 69, 98]
sum=len(scores)
if sum & 1: # % 2 == 1 -----> & 1
print('中心元素':scores[sum // 2])
else:
print('中心元素':scores[sum//2-1:sum//2 + 1])
# 或者print('中心元素:'scores[sum//2-1], scores[sum//2])
2.已知一个数字列表,求所有元素和。
scores =[34,56,78,90,24,35,46,58,69,98]
count = 0
for x in scores:
count += x
print(count)
3.已知一个数字列表,输出所有奇数下标元素。
scores =[34,56,78,90,24,35,46,58,69,98]
# 法1
for index in range (len(scores)):
if index & 1:
print(scores[index])
# 法2
print(index[1::2])
4.已知一个数字列表,输出所有元素中,值为奇数的元素。
scores = [10, 20, 1, 6, 84, 45, 64, 14]
for sum in scores:
if sum & 1:
print(sum)
5.已知一个数字列表,将所有元素乘二。
例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
# 法一:
scores =[34, 56, 78, 90, 24, 35, 46, 58, 69, 98]
for x in range(len(scores)):
scores[x] *=2
print(scores)
# 法二:
scores =[34, 56, 78, 90, 24, 35, 46, 58, 69, 98]
n_scores = []
for x in scores:
n_scores.append(x*2)
print(n_scores)
# 法三:(列表推导式)
new_nums = [x*2 for x in nums]
print(new_nums)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = [‘张三’, ‘李四’, ‘大黄’, ‘大黄’, ‘张三’, ‘张三’, ‘张三’] -> names = [‘张三’, ‘李四’, ‘大黄’]
法一:
names = ['张三', '李四', '大黄', '大黄', '张三', '张三', '张三']
sum = []
for x in range(len(names)):
for y in range(len(sum)):
if names[x] == sum[y]:
break
else:
sum.append(names[x])
print(sum)
法二:
names = ['张三', '李四', '大黄', '大黄', '张三', '张三', '张三']
new_name = []
for x in names:
if x not in new_name:
new_name.append(x)
print(new_name)
法三:
names = ['张三', '李四', '大黄', '大黄', '张三', '张三', '张三']
count = len(names)
for _ in range(count):
x = names.pop()
if x not in names:
names.insert(0, x)
print(names)
7.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
scores =[34, 56,120, 23,12,78, 90, 24,110]
sum=0
max=0
min=0
for x in range(len(scores)):
if scores[x] > scores[max]:
max=x
if scores[x] < scores[min]:
min=x
del scores[max]
del scores[min]
for i in range(len(scores)):
sum += scores[i]
print(sum/len(scores))
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 range(len(A)):
for y in range(len(B)):
if A[x] == B[y]:
C.append(A[x])
print(C)
9.*有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)
例如: nums = [19, 89, 90, 600, 1] —> 600
nums = [19, 89, 90, 600, 1]
max=0
for i in range(len(nums)):
if nums[i] > nums[max]:
max = i
print(nums[max])
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 = [1, 2, 3, 1, 4, 2, 1, 3, 7, 3, 3] count = [] # 创建一个空数组记录每一位数的出现次数 for x in range(len(nums)): count.append(0)#写入一个空的数据 for y in range(len(nums)): if nums[x] == nums[y]: count[x] += 1 sum = 0 for i in range(len(count)): if count[i] >= count[sum]: sum = i print(nums[sum])