如何在嵌套列表(list of lists)中筛选出ID以指定前缀开头的子列表
Filter Nested List by ID Prefix
Hey there! Let's solve this problem where we need to filter a nested list to return only the rows whose ID starts with a specific prefix.
First, let's recap our input data:
list_of_lists = [ ['ID', 'Last', 'First', 'GradYear', 'GradTerm', 'DegreeProgram'], ['101010', 'Lee', 'Shane', '2019', 'Spring', 'MSA'], ['101020', 'Zhang', 'Eve', '2019', 'Summer', 'MSSD'], ['101030', 'Anthony', 'Daisy', '2020', 'Fall', 'MSBA'] ]
Approach
The core idea here is straightforward:
- Keep the header row intact (since it doesn't contain an ID value)
- Iterate through the data rows and check if the first element (the ID) starts with our target prefix
- Combine the header with all matching data rows to preserve the original list structure
Solution Code
Here's a clean, reusable function to handle this:
def filter_by_id_prefix(data, prefix): # Grab the header row (first element of the nested list) header = data[0] # Use a list comprehension to filter rows where ID starts with the prefix filtered_data = [row for row in data[1:] if row[0].startswith(prefix)] # Return the header plus filtered rows to maintain consistency with input format return [header] + filtered_data # Example usage: Filter for IDs starting with "10" filtered_result = filter_by_id_prefix(list_of_lists, "10") # Print the result to verify for row in filtered_result: print(row)
How It Works
row[0]targets the ID column directly (since each sublist's first element is the ID)str.startswith(prefix)is ideal here—it efficiently checks if the ID string begins with our specified prefix, which aligns perfectly with the requirement- We separate the header from data rows upfront to avoid accidentally filtering out column names
Test Cases to Try
- Pass
"10101"as the prefix, and you'll only get the row with ID101010 - Use a non-matching prefix like
"99", and the result will just be the header row - An empty prefix (
"") will return all rows, since every string starts with an empty string
内容的提问来源于stack exchange,提问作者Hongteng Wang
相关产品推荐
相关产品推荐

