
1.已知一個列表,求列表中心元素。
list1 = ['a', 8, 'j', 1, 23]#index = 2
假如是偶數(shù) --list2= ['a', 8, 'j', 1, 8,23]#index= len(list2)//2 -1
num = len(list1)
if len(list1) % 2 != 0: # 列表個數(shù)是奇數(shù)
print(list1[len(list1) // 2])
2.已知一個列表,求所有元素和。
方法1
print(sum(list1))
方法2
list1 = [11, 2, 8, 9]
sum1 = 0
for index in range(len(list1)):
sum1 += list1[index]
print(sum1)
3.已知一個列表,輸出所有奇數(shù)下標元素。
list1 = [11, 2, 8, 9, 99, 77]
for index in range(len(list1)):
if index % 2 != 0:
print(list1[index])
4.已知一個列表,輸出所有元素中,值為奇數(shù)的。
list1 = [11, 2, 8, 9, 99, 77]
for index in range(len(list1)):
if list1[index] % 2 != 0:
print(list1[index])
5.已知一個列表,將所有元素乘二。
list1 = [11, 2, 8, 9]
list2 = []
for index in range(len(list1)):
num = list1[index] * 2
list2.append(num)
print(list2)
6.有一個長度是10的列表,數(shù)組內(nèi)有10個人名,要求去掉重復(fù)的
例如:names = ['張三', '李四', '大黃', '張三'] -> names = ['張三', '李四', '大黃']
方法一:
names1 = ['張三', '李四', '大黃', '張三', '王五', '張三', '大黃', '小黃', '張三', '王五']
name2 = []
for i in names1:
if i not in name2:
name2.append(i)
print(name2)
方法2
轉(zhuǎn)換成集合,然后遍歷
set1= set.name2
7.已知一個數(shù)字列表(數(shù)字大小在0~6535之間), 將列表轉(zhuǎn)換成數(shù)字對應(yīng)的字符列表
例如: 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.用一個列表來保存一個節(jié)目的所有分數(shù),求平均分數(shù)(去掉一個最高分,去掉一個最低分,求最后得分)
list1 = []
score = input('請輸入分數(shù):')
while score != 'end':
list1.append(int(score))
score = input('請輸入分數(shù):')
print(list1)
average = (sum(list1)-max(list1)-min(list1)) / (len(list1)-2)
print(average)
9.有兩個列表A和B,使用列表C來獲取兩個列表中公共的元素
例如: A = [1, 'a', 4, 90] B = ['a', 8, 'j', 1] --> C = [1, 'a']
list1 = [1, 'a', 4, 90]
list2 = ['a', 8, 'j', 1]
list3 = []
for index in range(len(list1)):
if list1[index] in list2:
list3.append(list1[index])
print(list3)