我想检查字符串列表中的字符串是否包含某个子字符串。如果他们这样做,我想将该列表项保存到新列表:
list = ["Maurice is smart","Maurice is dumb","pie","carrots"]
我尝试使用以下代码:
new_list = [s for s in list if 'Maurice' in list]
但如果其中一项为'Maurice'
,则只会复制该列表。
所以我想知道是否有一种方法可以通过使用以下语法来解决这个问题:
if "Maurice" in list:
# Code that saves all list items containing the substring "Maurice" to a new list
结果应为:
new_list = ["Maurice is smart", "Maurice is dumb"]
如果一直在寻找一种方法,但我找不到任何东西。
答案 0 :(得分:3)
你可以这样做:
list = ["Maurice is smart","Maurice is dumb","pie","carrots"]
new_list = [x for x in list if "Maurice" in x]
print(new_list)
输出:
['Maurice is smart', 'Maurice is dumb']
答案 1 :(得分:2)
您可以使用列表理解。
另外,请确保不要使用内置的list
作为变量名。
my_list = ["Maurice is smart", "Maurice is dumb", "pie", "carrots"]
[e for e in my_list if 'Maurice' in e]
答案 2 :(得分:2)
您可以使用Python的内置filter:
data = ["Maurice is smart", "Maurice is dumb", "pie", "carrots"]
res = filter(lambda s: 'Maurice' in s, data)
print(res)
输出:
['Maurice is smart', 'Maurice is dumb']
第一个参数是一个谓词函数(这里是一个简单的lambda),它必须求值为True才能将iterable的元素视为匹配。
只要必须根据谓词过滤iterable, filter
就很有用。
另外,还有一点,想象一下现在要过滤的数据:
data = ["Maurice is smart","Maurice is dumb","pie","carrots", "maurice in bikini"]
res = filter(lambda s: 'maurice' in s.lower(), list)
print(res)
输出继电器:
['Maurice is smart', 'Maurice is dumb', 'maurice in bikini']