如何在Python中按数字间隔遍历列表并筛选偶数?
Hey there! Let's break down how to solve this problem—traversing a list with a specified step interval, filtering out the even numbers, and formatting the output in a clean, readable way.
Solution Code & Explanation
Here's a complete, reusable implementation that covers all your requirements:
def process_list_with_step(input_list, step): # 1. Traverse the list with the specified step stepped_items = input_list[::step] # 2. Filter only even numbers from the stepped results even_numbers = [num for num in stepped_items if num % 2 == 0] # 3. Format and print the output (adjust this part if you need a specific format) print(f"✅ Elements picked with step {step}: {stepped_items}") print("\n🔍 Filtered even numbers:") for position, num in enumerate(even_numbers, start=1): print(f" {position}. {num}") # Test the function with a sample list sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] process_list_with_step(sample_list, 3)
Key Details Breakdown
- Traversing with Step: The slice syntax
input_list[::step]is Python's built-in way to grab elements at everystepinterval. For example, a step of 3 will pull elements at indices 0, 3, 6, 9, etc. - Filtering Evens: The list comprehension
[num for num in stepped_items if num % 2 == 0]efficiently filters out non-even numbers by checking if the remainder of division by 2 is 0. - Formatted Output: The print statements use f-strings for readability, and we enumerate the even numbers to add a numbered list—this makes the output easy to scan.
Sample Output
When you run the test code above, you'll get:
✅ Elements picked with step 3: [1, 4, 7, 10] 🔍 Filtered even numbers: 1. 4 2. 10
Customizing the Output Format
If you need a different output style (like comma-separated values or a single line), just tweak the print section. For example:
# Comma-separated output print(f"Filtered evens: {', '.join(map(str, even_numbers))}")
This would output: Filtered evens: 4, 10
内容的提问来源于stack exchange,提问作者Kuber
相关产品推荐
相关产品推荐

