Python 通过比较列表和字符串中的值来创建新列表
我有预定义列表中的元素和查询字符串。我想检查Python 通过比较列表和字符串中的值来创建新列表,python,string,list,Python,String,List,我有预定义列表中的元素和查询字符串。我想检查query\u str在预定义列表中是否有任何值,如果有,将它们作为单独的元素附加到新列表中 predefined_lst = ['hello', 'goodbye', 'see you later'] query_str = 'hello | are you having a nice day? see you later |' new_lst = [] 我有将字符串与列表中的值进行比较的语法,但无法将字符串中出现的值作为列表中的单个元素附
query\u str
在预定义列表中是否有任何值,如果有,将它们作为单独的元素附加到新列表中
predefined_lst = ['hello', 'goodbye', 'see you later']
query_str = 'hello | are you having a nice day? see you later |'
new_lst = []
我有将字符串与列表中的值进行比较的语法,但无法将字符串中出现的值作为列表中的单个元素附加到新列表中。
在上面的例子中,new\u lst
应该是new\u lst=['hello','see you later']
当我打印new\lst
时,我现在得到的结果就是真的
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)
您已经迷失在列表理解中:
new_lst = [string for string in predefined_lst if string in query_str]
当前,您正在将
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]
您可以使用来通过各种分隔符进行解析:
[i.strip() for i in re.split(r'[?|]',query_str) if i.strip() in predefined_lst]
或:
这是一个简单的解决方案:
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)
您正在将比较结果附加到新列表中。您应该追加的是字符串本身
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
另一种方法是使用
过滤器:
>>> 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']
“|”在他的字符串中不是一个特殊的符号。它不是分隔符。事实上,带有if
的那一行是一个语法错误。@kindall已修复。
>>> 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']