아두맨 아이디어 창작소

아두맨

아이디어 창작 도우미

    코딩/Python

    [python] 2중 리스트 기초 사용법

    아두맨 2023. 4. 9. 18:25

    학생 시험 점수를 분석하고 시각화하는 예제를 통해 2중 리스트를 배워보겠습니다.

     

    • 프로그램은 먼저 학생 결과 리스트를 입력으로 사용하고 평균 점수의 산점도를 생성하는 'visualize_average_scores' 함수를 정의합니다.
    • 학생 결과 데이터는 각 내부 리스트에 학생 이름과 5가지 다른 테스트 점수가 포함된 2중 리스트로 정의됩니다.
    • 'calculate_student_scores' 함수는 학생 결과 데이터에서 각 학생의 총점과 평균 점수를 계산하기 위해 정의됩니다.
    • 프로그램은 'calculate_student_scores' 함수를 호출하여 각 학생의 총점과 평균점수를 계산합니다.
    • 그런 다음 프로그램은 학급 평균을 계산하고 평균 점수가 가장 높은 학생과 가장 낮은 학생을 식별합니다.
    • 마지막으로 프로그램은 'visualize_average_scores' 함수를 호출하여 평균 점수의 산점도를 만들고 각 학생의 결과를 반복하여 각 테스트 간의 점수 차이를 계산합니다.

    전반적으로 이 프로그램은 Python이 데이터 분석 및 시각화, 특히 학생 시험 점수 분석에 어떻게 사용될 수 있는지에 대한 간단한 예입니다.

    import numpy as np
    import matplotlib.pyplot as plt
    
    def visualize_average_scores(student_results):
        # Get the average scores
        average_scores = [result[2] for result in student_results]
    
        # Create the scatter plot
        x = range(len(student_results))
        plt.plot(x, average_scores, '-o')
    
        # Add a title and labels
        plt.title("Distribution of Average Scores")
        plt.xlabel("Average Score")
        plt.ylabel("Frequency")
    
        # Show the plot
        plt.show()
    
    students_data = [
        ['James Lee', 85, 92, 80, 88, 90],
        ['Sarah Kim', 93, 87, 88, 90, 85],
        ['Michael Park', 89, 94, 87, 85, 92],
        ['Emily Choi', 91, 83, 90, 88, 85],
        ['David Kang', 87, 85, 83, 90, 89],
        ['Jennifer Lee', 90, 89, 92, 87, 84],
        ['Jason Lee', 92, 91, 89, 86, 88],
        ['Hannah Kim', 88, 90, 92, 89, 90],
        ['Kevin Song', 84, 88, 85, 91, 87],
        ['Jessica Lee', 89, 92, 87, 90, 83],
        ['Daniel Kim', 93, 86, 89, 85, 90],
        ['Rachel Park', 90, 93, 84, 87, 88],
        ['Brian Lee', 85, 89, 91, 84, 91],
        ['Ashley Kim', 91, 86, 90, 91, 86],
        ['Ethan Lee', 86, 91, 87, 92, 83],
        ['Caroline Choi', 93, 92, 89, 85, 88],
        ['Ryan Kim', 87, 84, 92, 90, 89],
        ['Grace Lee', 92, 90, 87, 88, 87],
        ['Justin Park', 88, 87, 84, 91, 91],
        ['Olivia Kim', 90, 89, 88, 87, 90]
    ]
    
    def calculate_student_scores(data):
        results = []
        for student in data:
            total_score = sum(student[1:])
            average_score = total_score / (len(student) - 1)
            results.append([student[0], total_score, average_score])
        return results
    
    student_results = calculate_student_scores(students_data)
    
    # Calculate class average
    class_average = np.mean([result[2] for result in student_results])
    print(f"Class Average: {class_average:.2f}")
    
    # Identify highest and lowest scoring students
    highest_scorer = max(student_results, key=lambda x: x[2])
    lowest_scorer = min(student_results, key=lambda x: x[2])
    
    print(f"Highest Scoring Student: {highest_scorer[0]}, Average Score: {highest_scorer[2]:.2f}")
    print(f"Lowest Scoring Student: {lowest_scorer[0]}, Average Score: {lowest_scorer[2]:.2f}")
    
    visualize_average_scores(student_results)
    
    # Analyze score improvements or declines across tests
    for student in student_results:
        name = student[0]
        score_differences = [student[j + 1] - student[j] for j in range(1, len(student) - 2)]

     

    출력 결과입니다.

     

     

    코드 단위로 분석해보겠습니다.

     

    def visualize_average_scores(student_results):
        # Get the average scores
        average_scores = [result[2] for result in student_results]
    
        # Create the scatter plot
        x = range(len(student_results))
        plt.plot(x, average_scores, '-o')
    
        # Add a title and labels
        plt.title("Distribution of Average Scores")
        plt.xlabel("Average Score")
        plt.ylabel("Frequency")
    
        # Show the plot
        plt.show()

    이 함수는 학생들의 시험 성적 데이터를 입력으로 받아서, 각 학생의 평균 성적을 산점도로 시각화합니다.

    함수의 첫 번째 줄에서는 입력으로 받은 student_results 리스트에서 각 학생의 평균 성적을 추출하여 average_scores 리스트에 저장합니다.

    다음으로, range() 함수를 사용하여 x 범위를 student_results 리스트의 길이에 따라 생성합니다. 이후 plt.plot() 함수를 사용하여 성적 분포를 산점도로 시각화합니다. 마지막으로, plt.title(), plt.xlabel(), plt.ylabel(), plt.show() 함수를 사용하여 산점도의 제목과 축 레이블을 설정하고, 산점도를 표시합니다.

     

    calculate_student_scores 함수는 다음과 같이 작성되어 있습니다.

     

    def calculate_student_scores(data):
        results = []
        for student in data:
            total_score = sum(student[1:])
            average_score = total_score / (len(student) - 1)
            results.append([student[0], total_score, average_score])
        return results

    이 함수는 학생들의 시험 성적 데이터를 입력으로 받아서, 각 학생의 총점과 평균 성적을 계산합니다. 이 함수는 결과를 2차원 리스트로 반환합니다.

    함수의 첫 번째 줄에서는 빈 리스트인 results를 정의합니다. 이후 for 루프를 사용하여 data 리스트 안에 있는 각 학생의 총점과 평균 성적을 계산합니다. total_score 변수에는 sum() 함수를 사용하여 학생의 시험 성적 총합을 계산하고, average_score 변수에는 시험 성적의 총합을 시험 수로 나눈 값을 저장합니다. 마지막으로, 각 학생의 이름, 총점, 평균 성적을 하나의 리스트로 묶어 results 리스트에 추가합니다.

     

    student_results = calculate_student_scores(students_data)
    
    # Calculate class average
    class_average = np.mean([result[2] for result in student_results])
    print(f"Class Average: {class_average:.2f}")
    
    # Identify highest and lowest scoring students
    highest_scorer = max(student_results, key=lambda x: x[2])
    lowest_scorer = min(student_results, key=lambda x: x[2])
    
    print(f"Highest Scoring Student: {highest_scorer[0]}, Average Score: {highest_scorer[2]:.2f}")
    print(f"Lowest Scoring Student: {lowest_scorer[0]}, Average Score: {lowest_scorer[2]:.2f}")
    
    visualize_average_scores(student_results)
    
    # Analyze score improvements or declines across tests
    for student in student_results:
        name = student[0]
        score_differences = [student[j + 1] - student[j] for j in range(1, len(student) - 2)]

    'visualize_average_scores' 함수는 'student_results' 리스트를 입력으로 받아 학생의 평균 점수에 대한 산점도를 생성합니다. 'calculate_student_scores' 함수는 'students_data' 리스트을 입력으로 받아 각 학생의 총점과 평균 점수를 계산하고 결과를 2중 리스트로 반환합니다.

    visualize_average_scores 기능은 먼저 student_results 리스트에서 각 학생의 평균 점수를 추출하여 average_scores 리스트에 저장합니다. 그런 다음 student_results 리스트의 길이를 기반으로 range() 함수를 사용하여 x축에 대한 범위를 만듭니다. 그런 다음 plt.plot() 함수를 사용하여 평균 점수의 산점도를 만들고 -o 인수는 각 포인트가 원으로 표시되어야 함을 나타냅니다. 마지막으로 plt.title(), plt.xlabel() 및 plt.ylabel() 함수를 사용하여 x 및 y축에 대한 제목과 레이블을 추가하고 plt를 사용하여 플롯을 표시합니다. .show() 함수.


    calculate_student_scores 함수는 먼저 results라는 빈 리스트을 정의합니다. 그런 다음 'for' 루프를 사용하여 '데이터' 리스트의 각 학생을 반복하고 총점과 평균 점수를 계산합니다. total_score 변수는 sum() 함수를 사용하여 첫 번째 요소(이름)를 제외한 학생의 모든 시험 점수를 더하여 계산합니다. 'average_score' 변수는 'total_score'를 응시한 테스트 수로 나누어 계산합니다. 마지막으로 'results' 리스트에 학생 이름, 총점, 평균 점수가 새 리스트로 추가됩니다. 그러면 'results' 리스트 함수 끝에 반환됩니다.

    '코딩 > Python' 카테고리의 다른 글

    [python] strip().split() 사용하여 데이터 전처리 하는법  (0) 2023.04.09
    [python] 정규식 compile로 웹크롤링 데이터 불러오기  (0) 2023.04.06
    [Python] 간단한 체스 나이트 이동 코드  (0) 2023.04.03

    '코딩/Python'의 다른글

    • 현재글[python] 2중 리스트 기초 사용법

    관련글

    • [python] strip().split() 사용하여 데이터 전처리 하는법 2023.04.09
    • [python] 정규식 compile로 웹크롤링 데이터 불러오기 2023.04.06
    • [Python] 간단한 체스 나이트 이동 코드 2023.04.03
    프로필사진

    아이디어를 실현시켜드립니다!

    • 최신글 전체보기 (29)
      • 코딩 (10)
        • Python (4)
        • C# (6)
      • ESP32 (12)
        • 장치설정 (9)
        • 센서활용 (2)
        • ESP32 프로젝트 (1)
      • 아두이노 (4)
        • 장치설정 (3)
        • 아두이노 프로젝트 (1)
      • 라즈베리파이 (1)
        • 라즈베리파이 프로젝트 (1)
      • 블로그 관련 (1)

    최근글과 인기글

    • 최근글
    • 인기글

    공지사항

    Tag

    개발, 데이터, 시제품, deepsleep, c#, 전력관리, LED, 아두맨, 의뢰, 딥슬립, 2중리스트, 웹, ESP32, st7789, 아두이노, 라즈베리파이, Arduino, wokwi, 아두이노 딥슬립, 2중 리스트,

    최근댓글

    Copyright 아두맨. All rights reserved.

    티스토리툴바