1.已知一个数字列表,求列表中心元素。
nums = [1,2,3,4,5]
media_nums = int((1+len(nums))/2)
print(nums[media_nums-1]) # 3
2.已知一个数字列表,求所有元素和。
nums = [1,2,3,4,5]
sum = 0
for x in nums:
sum += x
print(sum) # 15
3.已知一个数字列表,输出所有奇数下标元素。
nums = [1,2,3,4,5]
for index in range(1,len(nums),2):
print(index , nums[index])
4.已知一个数字列表,输出所有元素中,值为奇数的元素。
nums = [1,2,3,4,5]
for x in nums:
if x & 1:
print(x) # 1 3 5
5.已知一个数字列表,将所有元素乘二。
nums = [1,2,3,4,5] new_nums = [] for x in nums: element = x * 2 new_nums.append(element) print(new_nums) # [2, 4, 6, 8, 10]
6.有一个长度是7的列表,数组内有7个人名,要求去掉重复的
例如:names = [‘张三’, ‘李四’, ‘大黄’, ‘大黄’, ‘张三’, ‘张三’, ‘张三’] -> names = [‘张三’, ‘李四’, ‘大黄’]
names = ['张三', '李四', '大黄', '大黄', '张三', '张三', '张三'] new_names = [] for x in names: if x not in new_names: new_names.append(x) print(new_names)
7.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
scores = [7,8,9,10,9]
high= scores[0]
low = scores[0]
for x in scores:
if high <= x:
high = x
if low >= x:
low = x
scores.remove(high)
scores.remove(low)
sum = 0
for x in scores:
sum += x
print(sum/len(scores)) # 8.666666666666666
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 A:
for y in B:
if x == y:
C.append(y)
print(C) # [1, 'a']
9.*有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)
例如: nums = [19, 89, 90, 600, 1] —> 600
nums = [19, 89, 90, 600, 1]
max = nums[0]
for x in nums:
if x >= max:
max = x
print(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]
new = []
new_count= []
for x in nums:
if x not in new:
new.append(x)
print(new)
for x in new:
num = 0
for y in nums:
if x == y:
num += 1
new_count.append(num)
print(new_count)
max_index = new_count.index(max(new_count))
max = new[max_index]
print(max)