You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

列表元素操作需求:移除匹配子串元素及替换指定内容

Hey there, let's work through these two list manipulation tasks you've got. Here's straightforward, Python-based solutions for each:

1. Remove all list elements containing a specified substring

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.

2. Transform elements in the specified list

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:22:47