day-4 list job

1. Given a list of numbers, find the center element of the list.

list1 = [99, 2, 35, 55, 9, 12, 2]
if len(list1) & 1:
    print(list1[len(list1)//2])
else:
    print(list1[len(list1)//2-1], list1[len(list1)//2])

2. Given a list of numbers, find the sum of all elements.

list1 = [99, 2, 35, 55, 9, 12, 2]
print(sum(list1))

3. Given a list of numbers, output all odd subscript elements.

list1 = [99, 2, 35, 55, 9, 12, 2]
for i in range(1,len(list1),2):
    print(list1[i])

4. Given a list of numbers, output all elements with odd values.

list1 = [99, 2, 35, 55, 9, 12, 2]
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]

nums = [1, 2, 3, 4]
for i in range(len(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 = ['张三', '李四', '大黄', '张三', '陈冠希', '吴亦凡', '蔡徐坤', '张三', '黄子韬', '大黄']
new_names = []
for name in names:
    if name not in new_names:
        new_names.append(name)
print(new_names)

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)

list1 = [99, 2, 35, 55, 9, 12, 2]
list1.remove(min(list1))
list1.remove(max(list1))
print(sum(list1)/len(list1))

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 a in A:
    for b in B:
        if a == b:
            C.append(a)
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 = [19, 89, 90, 600, 1]
max_num = nums[0]
for num in nums[1::]:
    if num > max_num:
        max_num = num
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, 3, 2, 1, 3, 7, 3, 3, 5, 5, 5, 5, 5]
count = 0
element_list = []
for num in nums:
    if nums.count(num) > count:
        count = nums.count(num)
for num1 in nums:
    if nums.count(num1) == count and num1 not in element_list:
        element_list.append(num1)
print(element_list)

Guess you like

Origin blog.csdn.net/xdhmanan/article/details/108842528
Recommended