1.已知一个数字列表,求列表中心元素。
nums = [1, 3, 5, 2, 4, 6, 7, 8, 9]
print(nums[len(nums)//2])
2.已知一个数字列表,求所有元素和。
nums = [1, 3, 5, 2, 4, 6, 7, 8, 9]
sum = 0
for x in range(len(nums)):
sum += nums[x]
print(sum)
3.已知一个数字列表,输出所有奇数下标元素。
nums = [1, 3, 5, 2, 4, 6, 7, 8, 9]
for x in range(len(nums)):
if x & 1:
print(nums[x], end=' ')
4.已知一个数字列表,输出所有元素中,值为奇数的元素。
nums = [1, 3, 5, 2, 4, 6, 7, 8, 9]
for x in range(len(nums)):
if nums[x] & 1:
print(nums[x], end=' ')
5.已知一个数字列表,将所有0元素乘二。
例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
nums = [1, 3, 5, 2, 4, 6, 7, 8, 9]
for x in range(len(nums)):
nums[x] = nums[x] * 2
print(nums)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = [‘张三’, ‘李四’, ‘大黄’, ‘大黄’, ‘张三’, ‘张三’, ‘张三’] -> names = [‘张三’, ‘李四’, ‘大黄’]
names = ['张三', '李四', '大黄', '李四', '大黄', '李四', '张三', '李四', '张三', '张三']
name1 = []
for x in range(len(names)):
if names[x] not in name1:
name1.append(names[x])
print(name1)
7.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
nums = [1, 3, 5, 2, 4, 6, 7, 8, 9]
maxn = nums[0]
minn = nums[0]
sum = 0
for x in range(len(nums)):
sum += nums[x]
if nums[x] >= maxn:
maxn = nums[x]
if nums[x] <= minn:
minn = nums[x]
print((sum-maxn-minn)/(len(nums)-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 x in range(len(A)):
if A[x] in B:
C.append(A[x])
print(C)
9.*有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)
例如: nums = [19, 89, 90, 600, 1] —> 600
nums = [19, 89, 90, 600, 1]
maxn = nums[0]
for x in range(len(nums)):
if nums[x] >= maxn:
maxn = nums[x]
print(maxn)
10.*获取列表中出现次数最多的元素
例如:nums = [1, 2, 3,1,4,2,1,3,7,3,3] —> 打印:3
num = [1, 2, 3, 1, 4, 2, 1, 3, 7, 3, 3]
new_num = []
for i in num:
if i not in new_num:
new_num.append(i)
for j in new_num:
print('%s--数量%d' % (j,num.count(j)))
nums = [1, 2, 3, 1, 4, 2, 1, 3, 7, 3, 3]
dict_cnt = {}
for item in nums:
if item in dict_cnt:
dict_cnt[item] += 1
else:
dict_cnt[item] = 1
maxnum = list(dict_cnt.keys())[list(dict_cnt.values()).index(max(dict_cnt.values()))]
print("数量最多的key值为:", maxnum)