Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the application method of Python list and tuple

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the application of Python list and tuple". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what is the application of Python lists and tuples?"

Classic case 1: score sheet and average score statistics.

Description: enter the examination scores of 5 students in 3 courses, and calculate the average score of each student and the average score of each course.

We have talked about this case before and reminded you of the holes you should avoid when using nested lists. Here is the complete code.

"

Enter the examination results of 5 students in 3 courses

Calculate the average score of each student and the average score of each course

Version: 0.1

Author: Luo Hao

"

Names = ['Guan Yu', 'Zhang Fei', 'Zhao Yun','Ma Chao', 'Huang Zhong']

Courses = ['Chinese', 'Mathematics', 'English']

# create a nested list to save the scores of 5 students in 3 courses

Scores = [[0] * len (courses) for _ in range (len (names))]

# enter data

For I, name in enumerate (names):

Print (please enter the score of {name} = = >')

For j, course in enumerate (courses):

Scores [I] [j] = float (input (f'{course}:'))

Print ()

Print ('-'* 5, 'student average','-'* 5)

# calculate the average score of each person

For index, name in enumerate (names):

Avg_score = sum (index) / len (courses)

The average score of print (f'{name} is: {avg_score:.1f}')

Print ()

Print ('-'* 5, 'course average','-'* 5)

# calculate the average grade point of each course

For index, course in enumerate (courses):

# create a new list by generating the specified column from the scores

Curr_course_scores = [index] for score in scores]

Avg_score = sum (curr_course_scores) / len (names)

The average score of print (f'{course} is: {avg_score:.1f}')

The enumerate function is used when traversing the list above, which is very useful. We talked about two ways to loop through a list, one is to loop through the index, and the other is to traverse the list elements directly. The list processed by enumerate will get a tuple when it is iterated. After unpacking, the first value is the index and the second value is the element. Here is a simple comparison.

Items = ['Python',' Java', 'Go',' Swift']

For index in range (len (items)):

Print (f'{index}: {items [index]}')

For index, item in enumerate (items):

Print (f'{index}: {item}') case 2: design a function to return the day of the year that the specified date is.

Explanation: this case is derived from the famous example on The C Programming Language.

"

The day of the year is calculated as the day of the year

Version: 0.1

Author: Luo Hao

"

Def is_leap_year (year):

"determines whether the specified year is a leap year. The normal year returns False, and the leap year returns True".

Return year% 4 = = 0 and year% 100! = 0 or year% 400 = = 0def which_day (year, month, date):

The date of the calculation is the day of the year.

: param year: year

: param month: month

: param date: day

"

# use nested lists to save the number of days per month in normal and leap years

Days_of_month = [

[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

]

# Boolean values False and True can be converted to integers 0 and 1, so

# select the first list in the nested list (February is 28 days)

# Leap years select the second list in the nested list (February is 29 days)

Days = days_of_ month [is _ leap_year (year)]

Total = 0

For index in range (month-1):

Total + = days [index]

Return total + dateprint (which_day (1980, 11, 28)) # 333

Print (which_day (1981, 12, 31)) # 365

Print (which_day (2018, 1,1)) # 1

Print (which_day (2016, 3, 1)) # 61 case 3: realize the random selection of two-color spheres.

Description: the two-color ball belongs to the category of caipiao, which is uniformly organized and issued by China Welfare caipiao Distribution and Management Center and sold throughout the country. The range of red ball numbers is 01x 33 and the range of blue ball numbers is 01x 16. The two-color ball issues 6 numbers from 33 red balls and 1 number from 16 blue balls as the winning number. the double-color ball game is to guess the 6 red ball numbers and 1 blue ball number of the winning number.

The idea of this topic is to use a list to save the number of the red ball, and then use the sample function of the random module to achieve non-return sampling, so that you can extract six non-repetitive red ball numbers. Red balls need to be sorted. You can use the sort method of the list. When displaying a number, you need to fill in 0 in front of a digit, and you can use string formatting to deal with it.

"

Two-color sphere random number selection

Version: 0.1

Author: Luo Hao

"

From random import randint, sampledef display (balls):

"two-color ball number in the output list"

For index, ball in enumerate (balls):

If index = = len (balls)-1:

Print ('|', end='')

Print (f'{ball:0 > 2d}', end='')

Print () def random_select ():

"" randomly select a set of numbers ""

# generate red balls from No. 1 to No. 33 by generating formula

Red_balls = [x for x in range (1,34)]

# six red balls are selected by random sampling without putting them back

Selected_balls = sample (red_balls, 6)

# sort the red balls

Selected_balls.sort ()

# represent the selected blue ball with a random number from 1 to 16 and append it to the list

Selected_balls.append (randint (1,16))

Return selected_ballsn = int (input ('Machine selection Note:')

For _ in range (n):

Display (random_select ())

Warm Tip: the essence of caipiao is to make up a thing that gets something for nothing, to fool a group of people who want to get something for nothing, and finally to feed a group of people who really get something for nothing. Therefore, cherish life and stay away from all forms of dubo.

Case 4: lucky woman.

Explanation: there are 15 men and 15 women in distress at sea. In order to keep some of them alive, 15 of them had to be thrown into the sea. One man thought of a way to make everyone form a circle. The person who reported from 1 to 9 was thrown into the sea. The person behind him then counted from 1 to 9 and continued to throw 15 people into the sea until 15 people were thrown into the sea. In the end, 15 women survived and 15 men were thrown into the sea. Ask these people how they stood at first, which positions were men and which positions were women.

The above problem is actually the famous Joseph ring problem. We can use a list to save whether the 30 people are dead or alive, for example, using a Boolean value of True to represent those who are alive, and using False to represent those who have been thrown into the sea. At the beginning, the 30 elements in the list are all True, and then we loop to count, find the person to throw into the sea and mark the corresponding list element as False. The loop executes until the 15 elements in the list are marked as False. During the loop, the index of the list is always in the range of 0 to 29, and when it exceeds 29, it returns to 0, which happens to form a closed loop.

"

Lucky woman (Joseph ring problem)

Version: 0.1

Author: Luo Hao

"

Persons = [True] * 30

# counter-number of people thrown into the sea

# index-Index of the access list

# number-the number of numbers reported

Counter, index, number = 0,0,0

While counter < 15:

If persons [index]:

Number + = 1

If number = = 9:

Persons [index] = False

Counter + = 1

Number = 0

Index + = 1

Index% = 30

For person in persons:

Print ('female' if person else 'male', end='') so far, I believe you have a deeper understanding of "what is the application of Python lists and tuples". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report