如何在Python 3中按需求修改列表?添加9000相关实现方法
First, let's break down the pattern by comparing your original list and desired result to figure out the rule:
| Original Value | Result Value | Action Taken |
|---|---|---|
| 1 | 9001 | 1 + 9000 = 9001 |
| 2 | 9002 | 2 + 9000 = 9002 |
| 9007 | 9007 | Left unchanged (value ≥ 9000) |
| 7 | 9007 | 7 + 9000 = 9007 |
| 9001 | 9001 | Left unchanged (value ≥ 9000) |
| 45 | 9045 | 45 + 9000 = 9045 |
| 67 | 9067 | 67 + 9000 = 9067 |
| 33 | 9033 | 33 + 9000 = 9033 |
| 9033 | 9033 | Left unchanged (value ≥ 9000) |
The core logic is straightforward: For every element in the list, add 9000 to it if it’s less than 9000; keep it as-is if it’s 9000 or larger.
Method 1: Pythonic List Comprehension (Recommended)
This is the most concise and idiomatic way to implement this in Python:
original_list = [1, 2, 9007, 7, 9001, 45, 67, 33, 9033] result_list = [x + 9000 if x < 9000 else x for x in original_list] print(result_list) # Output: [9001, 9002, 9007, 9007, 9001, 9045, 9067, 9033, 9033]
The list comprehension loops through each element x in the original list. For each item, it checks if x is below 9000—if yes, it adds 9000; otherwise, it retains the original value.
Method 2: Explicit For Loop (Great for Beginners)
If you want a more step-by-step approach to understand the logic, use a standard for loop:
original_list = [1, 2, 9007, 7, 9001, 45, 67, 33, 9033] result_list = [] for num in original_list: if num < 9000: result_list.append(num + 9000) else: result_list.append(num) print(result_list) # Output: [9001, 9002, 9007, 9007, 9001, 9045, 9067, 9033, 9033]
Here, we start with an empty result list, iterate over each number in the original list, apply our rule, and append the modified (or original) value to the result list.
Both methods will produce exactly the output you’re looking for. The list comprehension is generally preferred in Python for its brevity and readability once you’re comfortable with the syntax.
内容的提问来源于stack exchange,提问作者Pydavide

