列表元素操作需求:移除匹配子串元素及替换指定内容
Hey there, let's work through these two list manipulation tasks you've got. Here's straightforward, Python-based solutions for each:
The key here is to filter out any elements that include your target substring. A list comprehension is perfect for this—it's concise and readable.
Example implementation:
def remove_elements_with_substring(input_list, target_substring): # Keep only elements that DON'T have the target substring return [item for item in input_list if target_substring not in item] # Test case my_list = ["cat", "dog", "black cat", "bird"] filtered_list = remove_elements_with_substring(my_list, "cat") print(filtered_list) # Output: ['dog', 'bird']
This function checks every element in your input list. If the target substring isn't present in an element, it gets kept in the new list; elements with the substring get excluded entirely.
For your given list, we need to replace elements that contain 'None' or 'Not Chosen' with a doubled version of that keyword, while leaving other elements untouched. Here's how to do it:
Solution code (readable loop version):
original_list = ['None, Pink, Green', 'Blue, Not Chosen', 'Red', 'Blue', 'Green, Red'] processed_list = [] for item in original_list: if 'None' in item: processed_list.append('None, None') elif 'Not Chosen' in item: processed_list.append('Not Chosen, Not Chosen') else: processed_list.append(item) print(processed_list) # Output: ['None, None', 'Not Chosen, Not Chosen', 'Red', 'Blue', 'Green, Red']
Concise list comprehension version:
If you prefer shorter code, you can use a nested ternary in a list comprehension:
processed_list = [ 'None, None' if 'None' in item else 'Not Chosen, Not Chosen' if 'Not Chosen' in item else item for item in original_list ]
Both approaches will produce the exact target list you're aiming for. The loop is easier to follow if you're new to Python, while the list comprehension is a more idiomatic way to write this kind of transformation.
内容的提问来源于stack exchange,提问作者user11357465

