1. Given a list of numbers, find the center element of the list.
list1=[1,5,7,7,4,5,6]
a=0
for i in range(len(list1)):
if i & 1:
a+=1
else:
print(list1[a-1],list1[a])
print(list1[a])
2. Given a list of numbers, find the sum of all elements.
list1=[1,5,7,3,6,4,5]
sum=0
for i in list1:
sum+=i
print(sum)
3. Given a list of numbers, output all odd subscript elements.
list1 = [1, 5, 7, 3, 6, 4, 5]
for i in range(1, len(list1), 2):
print(list1[i])
4. Given a list of numbers, output all elements with odd values.
list1 = [1, 5, 7, 3, 6, 4, 5]
for i in list1:
if i & 1:
print(i)
5. Given a list of numbers, multiply all the elements by two.
For example: nums = [1, 2, 3, 4] —> nums = [2, 4, 6, 8]
list1 = [1, 5, 7, 3, 6, 4, 5]
lists = []
for i in list1:
i *= 2
lists.append(i)
list1=lists
print(list1)
# 方法二
for i in range(len(list1)):
nums[i]*=2
print(nums)
# 方法三
for i , j in enumerate(nums):
nums[i]*=2
print(nums)
6. There is a list of length 10, there are 10 names in the array, and the duplicates are required to be removed.
For example: names = ['张三','李四','大黄','张三'] -> names = [ 'Zhang San','Li Si','Rhubarb']
# 方法一
names = ['张三', '李四', '大黄', '张三', '11', '11', '15', '18', '35', '19']
names2=[]
for i in range(len(names) - 1, -1, -1):
for j in range(len(names) - 1, i, -1):
if names[i] == names[j]:
del names[j]
print(names)
# 方法二
names1 = ['张三', '李四', '大黄', '张三', '11', '11', '15', '18', '35', '19']
for i in names1[:]:
if names1.count(i)>1:
names1.remove(i)
print(names1)
# 方法三
names = ['张三', '李四', '大黄', '张三', '11', '11', '15', '18', '35', '19']
names2=[]
for i in names:
if i not in names2:
names2.append(i)
print(names2)
7. Use a list to save all scores of a program and find the average score (remove a highest score, remove a lowest score, and find the final score)
grade = [1, 9, 3, 5, 6, 4]
grade.remove(max(grade))
grade.remove(min(grade))
print(len(grade))
print(sum(grade) / len(grade))
8. There are two lists A and B. Use list C to get the common elements in the two lists.
For example: 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 i in A:
if i in B:
c.append(i)
print(c)
9. There is a list of numbers, get the maximum value in this list. (Note: the max function cannot be used)
For example: nums = [19, 89, 90, 600, 1] —> 600
nums = [1, 7, 3, 4, 15, 20, 1, 3]
for i in range(len(nums) - 1, -1, -1):
for j in range(len(nums) - 1, i - 2, -1):
if nums[i] > nums[j]:
del nums[j]
print(nums)
# 方法二
nums = [1, 7, 3, 4, 15, 20, 1, 3]
max_num=nums[0]
for i in nums[1:]:
if i>max_nums:
max_num=i
print(max_num)
10. Get the most frequent element in the list
For example: nums = [1, 2, 3,1,4,2,1,3,7,3,3] —> Print: 3
nums = [1, 2, 3, 1, 4, 2, 1, 3,7,3,3,7,7,7,7,7,7,5,5]
max_nums=0
for i in nums:
count=nums.count(i)
if count > max_nums:
max_nums=count
new_num=[]
for j in nums:
if nums.count(j) == max_nums and j not in new_num:
new_num.append(j)
print(new_num)