Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python Sequence Structures: A Practical Guide

Tech May 17 2

Experiment Objectives

This guide demonstrates practical applications of Python's sequence data structures, including lists, tuples, dictionaries, and sets. The objectives are to:

  • Master Python's built-in sequence types: lists, tuples, dictionaries, and sets.
  • Understand how to manipulate these structures using operators and built-in functions.
  • Learn the mechanics of list comprehensions and generator expressions.
  • Apply slicing and sequence unpacking techniques.
  1. Storing Student Information

Store student details (ID, name, college, major) in a single variable using a dictionary.

info_fields = ['student_id', 'name', 'college', 'major']
student_profile = {}

for field in info_fields:
    student_profile[field] = input(f"Enter your {field}: ")

print("
Student Profile:")
for key, value in student_profile.items():
    print(f"{key}: {value}")

  1. Managing a Group Member List

Create a list to storre the names of group members.

group_members = []

num_members = int(input("How many members are in your group? "))
for _ in range(num_members):
    member_name = input("Enter a member's name: ")
    group_members.append(member_name)

print("
Group Members:", group_members)

  1. Modifying the Group List

Perform operations on the group list: add, remove, and update member names.

def manage_group_list(members):
    while True:
        print("
Current Members:", members)
        print("1. Add a member")
        print("2. Remove a member")
        print("3. Update a member's name")
        print("0. Exit")
        choice = input("Select an action: ")

        if choice == '1':
            new_member = input("Enter the name to add: ")
            members.append(new_member)
        elif choice == '2':
            name_to_remove = input("Enter the name to remove: ")
            if name_to_remove in members:
                members.remove(name_to_remove)
            else:
                print(f"{name_to_remove} not found in the list.")
        elif choice == '3':
            old_name = input("Enter the name to update: ")
            if old_name in members:
                new_name = input("Enter the new name: ")
                index = members.index(old_name)
                members[index] = new_name
            else:
                print(f"{old_name} not found in the list.")
        elif choice == '0':
            break
        else:
            print("Invalid choice. Please try again.")

manage_group_list(group_members)

  1. Extracting Unique Surnames

Input surnames and use a set to display the unique ones.

surnames_input = input("Enter group members' surnames separated by space: ")
surnames_set = set(surnames_input.split())

print("
Unique Surnames in the Group:", surnames_set)

  1. Calculating Group Statistics

Store member names and their Python scores, then calculate total members, total score, and average score.

member_scores = []

num_members = int(input("How many members' scores to enter? "))
for i in range(num_members):
    name = input(f"Enter name for member {i+1}: ")
    score = int(input(f"Enter {name}'s score: "))
    member_scores.append((name, score))

total_members = len(member_scores)
total_score = sum(score for _, score in member_scores)
average_score = total_score / total_members

print(f"
Total Members: {total_members}")
print(f"Total Score: {total_score}")
print(f"Average Score: {average_score:.2f}")

  1. Filtering Failing Scores

Use a list comprehension to filter out scores that are below 60.

all_scores = list(map(int, input("Enter scores separated by space: ").split()))
failing_scores = [score for score in all_scores if score < 60]

print("Scores below 60:", failing_scores)

  1. Extracting Integers from a Mixed List

Use a list comprehension to extract only the integer elements from a mixed-type list.

mixed_data = [123, 'hello', (1, 2), 456, {23}, {'a': 789}]
integers_only = [item for item in mixed_data if isinstance(item, int)]

print("Extracted integers:", integers_only)

  1. Using a Generator Expression

Generate numbers from 0 to 9, multip each by a lucky number, and convert the result to a list.

lucky_number = int(input("Enter your lucky number: "))

# Generator expression
generator = (num * lucky_number for num in range(10))

# Convert generator to a list
result_list = list(generator)

print("Generated and multiplied list:", result_list)

  1. Modifying a List with insert() and Slicing

Transform a list using both the insert() method and slicing to achieve the same result.

original_list = ["今天", "天气", "真好"]
modified_list = original_list.copy()

# Method 1: Using insert()
modified_list.insert(1, '的')
modified_list.insert(3, '是')
modified_list.insert(5, '呀')
print("Using insert():", modified_list)

# Method 2: Using slicing
original_list = ["今天", "天气", "真好"]
modified_list = original_list.copy()
modified_list[1:1] = ['的']
modified_list[3:3] = ['是']
modified_list[5:5] = ['呀']
print("Using slicing:", modified_list)

  1. Shopping Cart Simulation

Simulate a shopping cart, calculate the total cost, and check against a user-provided budget.

shopping_cart = [
    {"name": "床", "price": 1999, "num": 1},
    {"name": "枕头", "price": 10, "num": 2},
    {"name": "被子", "price": 20, "num": 1}
]

print("Your Shopping Cart:")
for item in shopping_cart:
    print(f"- {item['name']}: {item['num']} x ${item['price']} = ${item['price'] * item['num']}")

cart_total = sum(item['price'] * item['num'] for item in shopping_cart)
budget = int(input("
Enter your total budget: "))

if cart_total > budget:
    print(f"Purchase failed. Insufficient funds. Total: ${cart_total}, Budget: ${budget}.")
else:
    print(f"Purchase successful! Total: ${cart_total}.")

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.