1.已知一个数字列表,求列表中心元素。
nums = [70, 99, 50, 87, 67, 30, 100]
if len(nums) % 2 == 0:
s = len(nums) // 2
print(nums[s-1] + nums[s])
else:
s = len(nums) // 2
print(nums[s])
2.已知一个数字列表,求所有元素和。
nums = [70, 99, 50, 87, 67, 30, 100]
sum1 = 0
for num1 in nums:
sum1 += num1
print(sum1)
3.已知一个数字列表,输出所有奇数下标元素。
nums = [70, 99, 50, 87, 67, 30, 100]
for index in range(1, len(nums), 2):
print(nums[index])
4.已知一个数字列表,输出所有元素中,值为奇数的。
nums = [70, 99, 50, 87, 67, 30, 100]
for num in nums:
if num % 2 == 1:
print(num)
5.已知一个数字列表,将所有元素乘二。
例如:nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
nums = [70, 99, 50, 87, 67, 30, 100]
for index in range(len(nums)):
nums[index] *= 2
print(nums)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = ['张三', '李四', '大黄', '张三'] -> names = ['张三', '李四', '大黄']
names = ['柚', '莲', '梓', '柏', '梓', '栴', '梅', '柚', '椿', '柚']
rep_name = []
for index in range(len(names)-1):
for index2 in range(index+1, len(names),):
if names[index] == names[index2]:
rep_name.append(names[index])
break
for name in rep_name:
names.remove(name)
print(names)
names = ['柚', '莲', '梓', '柏', '梓', '栴', '梅', '柚', '椿', '柚']
new_name = []
for name in names:
if name not in new_name:
new_name.append(name)
print(names)
names = ['柚', '莲', '梓', '柏', '梓', '栴', '梅', '柚', '椿', '柚']
for name in names[:]
if names.count(name) > 1:
names.remove(name)
print(names)
7.已经一个数字列表(数字大小在0~6535之间), 将列表转换成数字对应的字符列表
例如: list1 = [97, 98, 99] -> list1 = ['a', 'b', 'c']
list1 = [97, 98, 99]
for index in range(len(list1)):
list1[index] = chr(list1[index])
print(list1)
8.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
nums = [70, 99, 50, 87, 67, 30, 100]
nums.remove(max(nums))
nums.remove(min(nums))
sum1 = 0
count = 0
for num1 in nums:
sum1 += num1
count += 1
print(sum1/count)
avg = (sum(nums) - max(nums) - min(nums)) / (len(nums) - 2)
print(avg)
9.有两个列表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 a in A:
for b in B:
if a == b:
C.append(a)
print(C)
10.有一个数字列表,获取这个列表中的最大值.(注意: 不能使用max函数)
nums = [70, 99, 50, 87, 67, 30, 100]
if nums[0] > nums[1]:
max1 = nums[0]
else:
max1 = nums[1]
for index in range(2, len(nums)):
if max1 > nums[index]:
continue
else:
max1 = nums[index]
print(max1)
11.获取列表中出现次数最多的元素
例如: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]
count_list = []
for index in range(len(nums)-1):
count = 0
for index2 in range(index+1, len(nums),):
if nums[index] == nums[index2]:
count += 1
count_list.append(count)
print(nums[count_list.index(max(count_list))])
nums = [1, 2, 3, 1, 4, 2, 1, 3, 7, 3, 3]
max_count = 0 # 保存最大个数
num = None # 保存最大个数对应的元素 None代表空值
for item in nums:
count = nums.count(item)
if count > max_count:
max_count = count
num = item
print(num)