Related problems and code implementation of python for loop traversal (not all)

Posted by backinblack on Mon, 20 Sep 2021 17:19:01 +0200

Question 1: traverse the list and find the sum of 20 numbers         (   (there are two ways)

The first generates numbers from 1 to 21, that is, numbers from 1 to 20, a total of 20.

The code is as follows:

sum=0                                 #Assign a value of 0 to the variable sum to facilitate the addition of subsequent traversal elements
listB=[]                              #Define an empty list variable to store the numbers generated later
for i in range(1,21):                 #Here, you can also try to write range(20), which means that numbers with subscripts 0 to 19 are generated, that is, 20 numbers are generated. And range(len(1,21))
    listB.append(i)                   #Use the append() function to add elements to the end of the list,
    sum+=i                            #It means that sum will add the traversed i for each loop
print(sum)                            #Print sum
print(listB)                          #Print listB

The effects are as follows:

210
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

  The second method is to generate an unordered list (a function library 'random' that generates random numbers needs to be introduced)

code:

import random
sum=0
listB=[]                                 #Define an empty list variable to store the random numbers generated later
for i in range(1,21):                    #Here, you can also try to write range(20), which means that numbers with subscripts 0 to 19 are generated, that is, 20 numbers are generated. And range(len(1,21))
     listB.append(random.randint(1,66))  #The append() function is used to add elements to the end of the list, and the random() function randomly generates a number between 1 and 65 and writes it to the list
     for j in range(len(listB)):         #Use the for loop to traverse the list. Because the value of j is the length of the list, that is, a number, 20, j traverses the subscripts of the elements in the list, and then add them in turn under the loop to get the sum of the elements in the list
         sum+=listB[j]                   #It can also be written as sum=sum+listB[j]. It is recommended to write the code as shown in the figure to save time.
print(listB)                              #Print listB
print(sum)                                #Print sum

effect;

 [29, 50, 52, 65, 46, 53, 22, 14, 6, 33, 41, 26, 19, 24, 31, 47, 6, 53, 16, 20]
7647

  Second question: give two lists, store a set of data respectively, traverse and type out the names of people with scores of more than 60 points

code:

name=['king','Zhang','Lee']             #Define a list variable name to store three elements' Wang ',' Zhang 'and' Li '. Because the elements inside are Chinese characters and strings, quotation marks are required. For example, quotation marks are not required for numbers.
goal=[88,99,55]        #Define a list variable goal to store three elements, the numbers 88, 99 and 66
                                             
for i in range(len(goal)):                                   #(generally, it means that we have mentioned earlier, so we won't bother here)
    if goal[i]>60:                                           #if judgment statement (the statement should be followed by a colon) to judge whether the number in the goal list is greater than 60. if it meets the conditions, it will be output.
        print('People with scores over 60 have{}'.format(name[i]),end=' ')      #Placeholders are used here to format the output. From the previous traversal, it can be seen that the elements with subscript i meet the conditions. Therefore, if you want to print out the results greater than 60, you only need to look for the I element in the list name. Because printt ends with a newline by default, if you don't want one result per line, you can write end = 'to end with a space,

effect:  

There are Wang with a score of over 60 and Zhang with a score of over 60  

Three questions:   Take out the largest and smallest numbers in a list, (there are two methods)

The first method uses traversal to compare.
#Let's go in two steps

#First, check whether there is a list variable for storing numbers. If there is no list variable, it can be generated out of order. It has been previously. This is omitted

#Then, we define two variables, both assigned to the first element of the list. It can be printed after traversal judgment.

code:

import random
listNum=[]                      #Define a list variable listNum to store 20 randomly generated numbers
for i in range(20):                  #slightly
    listNum.append(random.randint(1,66)) #slightly

min=listNum[0]                      #Make the minimum value the first element in the list, and then get the minimum value by traversing and comparing the size
max=listNum[0]                      #Let the maximum value be the first element in the list, and then traverse and compare the size to obtain the maximum value
for j in range(len(listNum)):
    if listNum[j]<min:                #Because we set the minimum value as the first element, we need to traverse the listNum element, and use the if statement to judge whether the listNum element will be less than the traversal number every time. If so, we get the minimum value.
        min=listNum[j]                 #If all the numbers traversed are less than the initial number, the minimum value is obtained
    elif listNum[j]>max:                #max, similarly, omitted.
        max=listNum[j]
print(f'The randomly generated list is:{listNum}')     #Here we use f '{}' to format the output. In fact, its representation is similar to '{}'. Format, but it is simpler and convenient. See what you like.
print(f'The minimum number is:{min}')
print(f'The maximum number is:{max}')

effect:   The elements in our list are generated randomly, so the maximum and minimum values will be different.

The randomly generated list is: [9, 45, 40, 63, 56, 24, 8, 38, 61, 5, 6, 2, 59, 19, 42, 7, 43, 55, 8, 47]
The minimum number is: 2
Maximum number: 63  

The second method is implemented with the sort() function. (this is more concise)  

Still define a list with numbers first.

code:

import random
listNum=[]                                        #Define a list variable listNum to store 20 randomly generated numbers
for i in range(20):                           #slightly
    listNum.append(random.randint(1,66))          #slightly
    listNum.sort()                            #sort() function to sort the list. Generally, the list is arranged from small to large. If you want to arrange backwards (i.e. from large to small), you can add reverse=True, and then the following maximum position becomes the first one. Just change the description accordingly
print(listNum)
print(f'The maximum value is:{listNum[-1]}')                    #It means to take the last one in the list. The reverse sorting of the list starts from - 1, that is, the first subscript of the reverse sorting is - 1
print(f'The minimum value is:{listNum[0]}')       

effect:

[1, 3, 5, 6, 10, 12, 21, 24, 26, 34, 38, 42, 42, 46, 49, 53, 58, 64, 64, 64]
Maximum: 64
The minimum value is: 1   

Four questions: a classmate took four exams. Each time he took math and Chinese, which was the higher average score of Chinese and mathematics.

 

listGaol=[{'Chinese':120,'math':90},{'Chinese':130,'math':100},{'Chinese':110,'math':120},{'Chinese':120,'math':115}]#Add the results of each exam to a list. I took the exam four times, a total of four dictionaries
chinese=0
math=0
for i in range(len(listGaol)):
    chinese+=listGaol[i]['Chinese']         #Because this list contains other variable types (dictionaries), the index needs to be written twice to access the elements in it, and because the values of the dictionary are accessed through keys, the corresponding language key to be found is written in the following brackets,
    math+=listGaol[i]['math']         #Similarly
c=chinese/4                #Average
m=math/4
if c>m:
    print(f'The average score of Chinese is the highest, which is{c}branch')
else:
    print(f'The highest average score in mathematics is{m}branch')
print(f'The total score of Chinese is:{chinese},The average score is:{c}branch')
print(f'The total score of mathematics is:{math},The average score is;{m}branch')

effect:

The average score of Chinese is the highest, 120.0
The total score of Chinese is 480, and the average score is 120.0
The total score of mathematics is 425, and the average score is; 106.25 points  

  The above is my personal understanding. If there are any mistakes, please write to me and work hard together. Thank you~

 

Topics: Python Algorithm