Python 列表筛选包含特定字符的元素
使用列表推导式可以筛选出包含某个字的元素,例如:
my_list = ['apple', 'banana', 'orange', 'grape']
search_word = 'an'
result = [item for item in my_list if search_word in item]
print(result) # ['banana', 'orange']
这里使用了 if 条件语句来判断元素是否包含 search_word,如果包含则加入结果列表中。
原文地址: https://www.cveoy.top/t/topic/jBCx 著作权归作者所有。请勿转载和采集!