我在预定义列表和查询字符串中有元素。我想检查query_str
是否在预定义列表中有任何值,如果是,请将它们作为单独的元素附加到新列表中。
predefined_lst = ['hello', 'goodbye', 'see you later']
query_str = 'hello | are you having a nice day? see you later |'
new_lst = []
我有将字符串与列表中的值进行比较的语法,但是我无法将字符串中出现的值作为列表中的单个元素附加到新列表中。
在上面的示例中,new_lst
应为new_lst = ['hello', 'see you later']
。
当我打印new_lst
时,我现在得到的结果为True。
predefined_lst = ['hello', 'goodbye', 'see you later']
query_str = 'hello | are you having a nice day? see you later |'
new_lst = []
match = if any(string in query_str for string in predefined_lst)
new_lst.append(match)
print(new_lst)
答案 0 :(得分:6)
你在列表理解中迷失了:
beforeEach(inject(function ($controller, $rootScope, _GitUser) {
$controllerConstructor = $controller;
scope = $rootScope.$new();
GitUser = _GitUser;
}));
答案 1 :(得分:2)
目前,您要在行中True
或False
附加new_lst
,
match = if any(string in query_str for string in predefined_lst)
这是因为if ...
返回布尔值True
或False
。
相反,试试这个
for x in predefined_list:
if x in query_str:
new_list.append(x)
或者作为列表comp,
new_lst = [string for string in predefined_lst if string in query_str]
答案 2 :(得分:1)
另一种方法,使用filter
:
>>> predefined_lst = ['hello', 'goodbye', 'see you later']
>>> query_str = 'hello | are you having a nice day? see you later |'
>>>
>>> list(filter(lambda s: s in query_str, predefined_lst))
['hello', 'see you later']
答案 3 :(得分:0)
您可以使用passing parameters to includes通过各种分隔符进行解析:
<a href="{{part[1]}}"> {{part[0]}} </a>
或者:
[i.strip() for i in re.split(r'[?|]',query_str) if i.strip() in predefined_lst]
答案 4 :(得分:0)
这是一个简单的解决方案:
predefined_lst = ['hello', 'goodbye', 'see you later']
query_str = 'hello | are you having a nice day? see you later |'
new_lst = []
for item in predefined_lst:
if item in query_str:
new_lst.append(item)
print(new_lst)
答案 5 :(得分:0)
您要将比较结果附加到new_list。你应该追加的是字符串本身。
predefined_lst = ['hello', 'goodbye', 'see you later']
query_str = 'hello | are you having a nice day? see you later |'
new_lst = []
for str in predefined_lst:
if(str in query_str):
new_lst.append(str)
print new_lst