1.已知一个数字列表,求列表中心元素。
numbers = [1, 2, 43, 8, 234, 20, 32]
length = len(numbers)
if length % 2 == 0:
print(numbers[length//2-1:length//2+1])
else:
print(numbers[length//2])
2.已知一个数字列表,求所有元素和。
numbers = [1, 2, 43, 8, 234, 20, 32]
print(sum(numbers))
3.已知一个数字列表,输出所有奇数下标元素。
numbers = [1, 2, 43, 8, 234, 20, 32]
for index in range(len(numbers)):
if index % 2 != 0:
print(numbers[index])
# 方法二
print(numbers[1::2])
4.已知一个数字列表,输出所有元素中,值为奇数的。
numbers = [1, 2, 43, 8, 234, 20, 32]
for index in range(len(numbers)):
if numbers[index] % 2 != 0:
print(numbers[index])
5.已知一个数字列表,将所有元素乘二。
numbers = [1, 2, 43, 8, 234, 20, 32]
for index in range(len(numbers)):
numbers[index] *= 2
print(numbers)
6.有一个长度是10的列表,数组内有10个人名,要求去掉重复的
例如:names = ['张三', '李四', '大黄', '张三'] -> names = ['张三', '李四', '大黄']
# 方法1
names = ['张三', '李四', '王二', '六五', '李四']
names = list(set(names))
print(names)
# 方法2
names = ['张三', '李四', '王二', '六五', '李四']
for name in names:
if names.count(name) > 1:
names.remove(name)
print(names)
7.已知一个数字列表(数字大小在0~65535之间), 将列表转换成数字对应的字符列表
例如: list1 = [97, 98, 99] -> list1 = ['a', 'b', 'c']
numbers = [789, 23, 76, 897, 1234, 6536, 4396, 97]
for index in range(len(numbers)):
numbers[index] = chr(numbers[index])
print(numbers)
8.用一个列表来保存一个节目的所有分数,求平均分数(去掉一个最高分,去掉一个最低分,求最后得分)
numbers = [7, 8, 9, 6, 1, 6, 6, 7]
length = len(numbers)
least = min(numbers)
biggest = max(numbers)
result = (sum(numbers) - least - biggest) / (length - 2)
print('平均分是:%.2f' % result)
9.有两个列表A和B,使用列表C来获取两个列表中公共的元素
例如: A = [1, 'a', 4, 90] B = ['a', 8, 'j', 1] --> C = [1, 'a']
# 方法1
A = [1, 'a', 4, 90]
B = ['a', 8, 'j', 1]
C = []
for item1 in A:
if item1 in B and item1 not in C:
C.append(item1)
print(C)
# 方法2
C = list(set(A) & set(B))
print(C)
10.names = ['海贼王', '火影', '死神', '犬夜叉', '熊出没', '海贼王', '海贼王']
需求:删除所有的'海贼王' ,用remove,用del/pop
names = ['海贼王', '火影', '死神', '犬夜叉', '熊出没', '海贼王', '海贼王']
count = 0
for name in names:
if name == '海贼王':
count += 1
for times in range(count):
names.remove('海贼王')
print(names)