day6 list job

Posted by Waldir on Wed, 08 Dec 2021 12:55:43 +0100

day6. List basis

1. Operation

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

list1 = [18,99,87,54,63,54,55]
if len(list1) // 2 == 0:
    print(list[len(list1)//2],list[len(list1)//2-1])
eles:
    print(lsit[len(list1)//2])

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

list1 = [12,33,88,96,78]
sum = 0
for x in list1:
    sum += x
print(sum)

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

list1 = [10,22,33,44,55,66,77]
print(1::2)

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

list1=[13,54,66,39,45,22]
for x in list1:
    if x // 2 != 0:
        print(x)

5. Given a list of numbers, multiply all elements by two.

For example: num = [1, 2, 3, 4] - > num = [2, 4, 6, 8]

nums = [5,6,7,8,9]
for x in range(len(nums)):
    y = nums[x] * 2
    nums[x] = y
print(nums)

6. There is a list with a length of 10. There are 10 names in the array. It is required to remove the duplicate names

For example: names = ['Zhang San', 'Li Si', 'rhubarb', 'rhubarb', 'Zhang San', 'Zhang San', 'Zhang San'] - > Names = ['Zhang San', 'Li Si', 'rhubarb']

names = ['Zhang San', 'Li Si', 'chinese rhubarb', 'chinese rhubarb', 'Zhang San', 'Zhang San', 'Zhang San']
new_name = []
for x in names:
    if x not in new_name:
        new_name.append(x)
print(new_name) 

7. Use a list to save all scores of a program and calculate the average score (remove the highest score, remove the lowest score and calculate the final score)

list1=[7,8,9,6,5,4,9,8,10]
sums = 0
list1.pop(max(list1))
list1.pop(min(list1))
for x in list1:
    sum += x
print(sum / len(list1))

8. There are two lists A and B. use list C to obtain 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 x in A:
    if x in B and x in A:
        C.append(x)
print(C)

9. * there is a list of numbers to get the maximum value in this list. (Note: the max function cannot be used)

For example: num = [19, 89, 90, 600, 1] - > 600

nums = [19, 89, 90, 600, 1]       #be opportunistic
for x in range(len(nums)-1):
    nums.remove(min(nums))
print(nums)

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]
max_count = 0
for i in nums:
    count = nums.count(i)
    if count > max_count:
        max_count = count
new_num = []
for i in nums:
    if nums.count(i) == max_count and i not in new_num:
        new_num.append(i)
print(new_num)

2. List

1. Container data type (sequence)

"""
Containers can be divided into variables of non container data type and variables of container data type
Variables of non container data type - there is only one grid in a box, so only one data can be saved at a time. For example: int, float, bool, None
Container data type variable - there are multiple grids in a box. Each grid can store different data, so multiple data can be saved at the same time.
For example: list, dict, tuple, set, str, etc
"""

scores = [89,70,98,23,90,67,62,78,23,89]
print(sum(scores))
print(max(scores),min(scores))
2. What is a list

"""
The list is a container data type, with [] as the container flag, and multiple elements in it are separated by commas: [element 1, element 2, element 3,...]
The list is variable (variable means that the number, value and order of elements are variable - adding, deleting and modifying operations are supported); Ordered list (subscript operation is supported)
Elements in the list: any type of data can be used as elements of columns. (not required)

Element - refers to each individual data in the container
"""

#Empty list
list1 = []
print(list1)

#list2 is a list with only one element in it
list2 = [19]

list3 = [10,20,30]
print(list3)

#Elements in the same list can be different types of data
list4 = [10,'hello',12.8,True,[100,200]]
print(list4)

#Empty list
list1 = []
print(list1)

#list2 is a list with only one element in it
list2 = [19]

list3 = [10,20,30]
print(list3)

#Elements in the same list can be different types of data
list4 = [10,'hello',12.8,True,[100,200]]
print(list4)

3. Get list elements

1. Get a single element

"""
Syntax:
List [subscript] - get the elements corresponding to the subscript

explain:
List - the expression that holds the variables of the list,; For example, keep list variables or specific list data
[] - Fixed writing
Subscript - subscript (also known as index) is the position information of elements in an ordered sequence
The first one: increase from 0 from front to back
The second: from back to front, start from - 1 to reduce once

Note: the subscript cannot be out of bounds
"""

list1 = [10,20,30,40]
#[10,20,30,40][]
#list1[]
print(list1[0])   #Get the element with subscript 0 in list1 - > 10
print(list1[2])   #30
print(list1[-1])   #40
#print(list1[4])   #Error reporting: IndexError: list index out of range

2. Slice - get some elements
"""
Syntax 1:
List [start subscript: end subscript: step size]

1) If the direction from the start subscript to the end subscript is consistent with the direction corresponding to the step size (a positive step size means from front to back, and a negative step size means from back to front), the data can be obtained, otherwise the result is null
2) Determine the valid range: the element corresponding to the start subscript can be obtained, but the element corresponding to the end subscript cannot be obtained - > [start subscript, end subscript)
3) Determine the slice result: take the data according to the absolute value of the step within the effective range; take one by one when the absolute value is 1, and skip one by one when the absolute value is 2

"""

heroes = ['Asso','Kasha','EZ','czar','Male gun','Ali','Kitty','wet nurse']
#If the direction from the start subscript to the end subscript is consistent with the direction corresponding to the step size, the data can be obtained
print(heroes[0:2:1])     #['asso', 'kasha']
print(heroes[0:-1:1])     #['asso', 'kasha', 'EZ', 'Czar', 'male gun', 'Ali', 'cat']
print(heroes[-1:2:-1])      #['wet nurse', 'cat', 'Ali', 'male gun', 'Czar']

#If the direction from the start subscript to the end subscript is inconsistent with the direction corresponding to the step size, the data must not be obtained
print(heroes[1:4:-1])   #[]
print(heroes[5:1:2])   #[]

print(heroes[1:5:1])     #['kasha', 'EZ', 'Czar', 'male gun']

print(heroes[1:5:2])    #['kasha', 'Czar']
print(heroes[1:5:])     #['kasha', 'male gun']

#Exercise: write out the print result of the expression
heroes = ['Asso','Kasha','EZ','czar','Male gun','Ali','Kitty','wet nurse']
print(heroes[0:5:2])   #['asso', 'EZ', 'male gun']
print(heroes[1:-2:-1])   #[]
print(heroes[2:-2:2])    #['EZ', 'male gun']
print(heroes[-2:0:-3])    #['Czar', 'cat']
print(heroes[-1:-4:1])    #[]
print(heroes[0:6:3])    #['asso', 'Czar']

#Exercise 2: write slices to get the following assignments
#['EZ', 'Czar', 'male gun']
print(heroes[2:5:1])
#['asso', 'kasha', 'EZ', 'Czar']
print(heroes[0:4:1])
#['cat', 'Ali', 'male gun']
print(heroes[-2:-5:-1])
#['kasha', 'Czar', 'Ali']
print(heroes[1:-2:2])
#['nanny', 'Ali']
print(heroes[-1:-4:-2])
#['kasha', 'cat']
print(heroes[1:7:5])

"""
List [start subscript: end subscript: step size]
Syntax 2: omit step size
List [start subscript: end subscript] - step size is 1

Syntax 3: omit the starting subscript
List [: end subscript: step] / list [: end subscript]

Syntax 4: omit closing subscript
List [start subscript: step size] / list [start subscript:] - if the step size is positive, take it back from the first element; if the step size is negative, take it forward from the last element
If the step size is positive, it starts from the start subscript and ends from front to back; if the step size is negative, it starts from the start subscript and ends from back to front
"""

heroes = ['Asso','Kasha','EZ','czar','Male gun','Ali','Kitty','wet nurse']
print(heroes[1:3])  #['kasha', 'EZ']
print(heroes[1:-1])  #['kasha', 'EZ', 'Czar', 'male gun', 'Ali', 'cat']
print(heroes[3:0])   #[]

print(heroes[:3])   #['asso', 'kasha', 'EZ']
print(heroes[:3:-1])    #['wet nurse', 'cat', 'Ali', 'male gun']
print(heroes[:-2:2])    #['asso', 'EZ', 'male gun',]

print(heroes[3:])   #['Czar', 'male gun', 'Ali', 'cat', 'wet nurse']
print(heroes[-2::-2])    #['cat', 'male gun', 'EZ', 'asso']

print(heroes[::-1])   #['wet nurse', 'cat', 'Ali', 'male gun', 'Czar', 'EZ', 'kasha', 'yaso']

#Exercise: calculate the print result of the following expression
heroes = ['Asso','Kasha','EZ','czar','Male gun','Ali','Kitty','wet nurse']
print(heroes[2:5])   #['EZ', 'Czar', 'male gun']
print(heroes[3::-2])  #['Czar', 'kasha']
print(heroes[-3::-1])   #['Ali', 'male gun', 'Czar', 'EZ', 'kasha', 'Yasso']
print(heroes[:-4:2])   #['asso', 'EZ']
print(heroes[1::3])   #['kasha', 'male gun', 'wet nurse']
print(heroes[:-2])   #['asso', 'kasha', 'EZ', 'Czar', 'male gun', 'Ali']
3. Traversal - take out all one by one

"""
Method 1: get elements directly
for variable in list:
Circulatory body

The variable gets each element in the list at a time

Method 2: obtain the element by obtaining the subscript of each element
for variable in range:
Circulatory body

The subscript of the element in the list when the variable is obtained in turn

Supplement: len (list) - get the length of the list
"""

nums = [23,8.9,90,89,78.3]
for x in nums:
    print('x:',x)

print('----------------------------------------------')
for x in range(len(nums)):
    print(x,nums[x])

print('----------------------------------------------')
#-1,-2,-3,-4,-5
for x in range(-1,-len(nums)-1,-1):
    print(x,nums[x])

# Exercise: scores saves the scores of all students
# 1) Count the number of failed students
# 2) Calculate student average
scores = [90, 78, 54, 67, 88, 30, 59]
count = 0
sums = 0
for x in scores:
    sums +=x
    if x < 60:
        count+=1
print(count,'average',sums/len(scores))

# Exercise 2: given the list num, count the number of integers in num
nums = [90, 1.23, 'abc', 12, 0.12]
count = 0
for x in nums:
    if type(x) == int:
        count+=1
print(count)

4. Addition, deletion and modification

Add - add element

"""
1) List. Append (element) - adds an element to the end of the list
2) List. Insert (subscript, element) - inserts an element before the specified subscript

"""

#1)append
list1 = [10,20]
print(list1)

list1.append(100)
print(list1)     #[10,20,100]

#append instance
# Exercise: scores saves the scores of multiple students and extracts the failing scores from all the scores
scores = [90, 78, 65, 45, 55, 89, 30, 99]
#[45,55,30]
new_scores = []
for x in scores:
    if x < 60:
        new_scores.append(x)
print(new_scores)


#2)insert instance
nums = [10,20,30,40]
print(nums)   #[10,20,30,40]

nums.insert(1,100)
print(nums)   #[10,100,20,30,40]

# Exercise: given a list, the elements in the list have been arranged in order from small to large. Insert the input data. It is required that the order will not be affected after insertion
nums = [12, 23, 56, 78, 99, 120]
# 80   -> [12, 23, 56, 78, 80, 99, 120]
# 2    ->  [2, 12, 23, 56, 78, 99, 120]
value = 80
for x in range(len(nums)):
    if nums[x] >value:
        nums.insert(x,value)
        break
else:
    nums.append(value)
print(nums)
2. Delete - delete element

"""
Syntax 1:del list [subscript] - delete the element corresponding to the specified subscript
"""
tvs = ['pirate king', 'Seven Dragon Balls',' Langya list ',' biography of Zhen Huan ',' famous detective Conan ',' huanzhuge ']
print(tvs) #['pirate king', 'Seven Dragon Balls',' Langya list ',' Legend of Zhen Huan ',' famous detective Conan ',' huanzhuge ']

del tvs[1]
print(tvs) #['pirate king', 'Langya list', 'Legend of Zhen Huan', 'famous detective Conan', 'huanzhu gege']

"""
Syntax 2: list. Remove (element) - deletes the specified element
"""

tvs = ['One Piece', 'Dragon Ball','Legend of Zhen Huan', 'Nirvana in Fire', 'Legend of Zhen Huan', 'Detective Conan', 'Huanzhuge']
print(tvs)

tvs.remove('Huanzhuge')
print(tvs)

#tvs.remove('three countries')   #ValueError: list.remove(x): x not in list

tvs.remove('Legend of Zhen Huan')  #If there are duplicates, delete the first one
print(tvs)

"""
Grammar 3:list.pop()  -   Remove the last element
     list.pop(subscript)  -  Extract the element corresponding to the specified subscript,And return
"""
tvs = ['One Piece', 'Dragon Ball','Legend of Zhen Huan', 'Nirvana in Fire', 'Legend of Zhen Huan', 'Detective Conan', 'Huanzhuge']
tvs.pop()
print(tvs)   #['pirate king', 'Seven Dragon Balls',' Legend of Zhen Huan ',' Langya list ',' Legend of Zhen Huan ',' famous detective Conan ']

tvs.pop(1)
print(tvs)   #['pirate king', 'Legend of Zhen Huan', 'Langya list', 'Legend of Zhen Huan', 'famous detective Conan']

result = tvs.pop()
print(tvs,result)   #['pirate king', 'Legend of Zhen Huan', 'Langya list', 'Legend of Zhen Huan'] Detective Conan
3. Change

List [subscript] = value - change the element corresponding to the specified subscript in the list to the specified value

movies = ['The Shawshank Redemption','Marine pianist','Changjin Lake','Luo Xiaohei's War']
movies[0] = 'V Word vendetta team'
print(movies)   #['V-shaped revenge team', 'sea Pianist', 'Changjin Lake', 'Luo Xiaohei's war notes']

#Exercise: change all failed scores in scores to 0 - > [90,0,89,0,88]
scores = [90,34,89,55,88]
for x in range(len(scores)):
    if scores[x] < 60:
        scores[x] = 0
print(scores)

in operation

1.in

Element in list - determines whether the specified element exists in the list
Element not in list - determines whether the specified element does not exist in the list

print(10 in [10,20,30])   #True
print([10,20] in [10,20,30])   #False
print([10,20] in [[10,20],30])  #True

Topics: Algorithm leetcode