Python列表:使用for循环、replace函数替换元素并统计次数求助
Solution Using For Loop and Replace Function
Got it, let's build a Python script that checks all your boxes—using a for loop, the replace() function, counting replacements, and showing both original and modified lists. Here's the code:
# Define the original list as specified original_list = ["blue", "red", "yellow", "green", "red", "black", "white", "gray", "blue", "blue", "red"] # Get user input for target and replacement words target_word = input("Enter the target word: ") replace_word = input("Enter the replacement word: ") # Initialize empty list for modified words and counter for replacements modified_list = [] replace_count = 0 # Iterate through each word in the original list for word in original_list: # Use replace() to substitute target with replacement (works even for exact matches) new_word = word.replace(target_word, replace_word) modified_list.append(new_word) # Increment count only if the original word was the target (since replace changed it) if word == target_word: replace_count += 1 # Output the results in the requested format print("Original list:", ", ".join(original_list)) print(f"Replaced {replace_count} times") print("Modified list:", ", ".join(modified_list))
How it works:
- Original List: We start with the exact list you provided.
- User Input: The script asks for your target and replacement words (e.g., "red" and "pink").
- For Loop & Replace: For each word in the list, we use
replace()to swap the target word with the replacement. Since each element is a single word,replace()will either change it (if it's the target) or leave it as-is. - Counting Replacements: We check if the original word matched the target each time—if yes, we increment our counter to track how many times the swap happened.
- Output: We print the original list, the number of replacements, and the modified list in the comma-separated format you want.
Example Output:
If you input red as the target and pink as the replacement, you'll get:
Original list: blue, red, yellow, green, red, black, white, gray, blue, blue, red Replaced 3 times Modified list: blue, pink, yellow, green, pink, black, white, gray, blue, blue, pink
内容的提问来源于stack exchange,提问作者MikeVita4
相关产品推荐
相关产品推荐

