繁体   English   中英

Python 搜索所有 List1 并匹配 List2[s]

[英]Python search all of List1 and match against List2[s]

我正在编写一个脚本,如果一个或多个缺少list1一个术语,它会比较两个列表和输出。 最终目标是针对list2[0]搜索list1所有内容,然后是list2[1]等。如果没有匹配项,则附加到一个新列表,以便稍后打印出来。

list1是搜索,多个值,静态list2是要搜索的值,可能是 1 到 50 个值,具体取决于我从我解析的文件中抓取的输入。

list1 = ["color:", "size:", "tip:"]
list2 = ["color:red", "color:purple", "black", "size:2", "tip:small", "tip:large", "size:4", "2", "color:blue"]

在这里,我们看到 black 和 2 缺少list1一个参数。 这个想法是将["black", "2"]附加到一个新变量,稍后作为“缺少的参数”调用。 如果list1项目不存在,则用户通过list2进行的搜索将不起作用。

search_file = os.getcwd()+'/var/log/mysearch.csv'
searching = csv.reader(open(search_file, 'rt'), delimiter = ',')

list1 = ["color:", "size:", "tip:"]

for row in searching:
                search_query = urllib.parse.unquote(row[4]) #pulls row 4 from csv where search is. User enters the matching row number via command line to run a check. 
                if args.search_query == row[0]: # url decodes the search[4] based on row with id

                        newlist = []
                        #removed = (shlex.split(r)) #search might contain double quotes, split to list by spaces this would be my list2. An attempt to tokenize. 
                        # For ease of this post, I pasted the returned value from the search_file below that was converted with this command.

                        removed = ["color:red", "color:purple", "black", "size:2", "tip:small", "tip:large", "size:4", "2", "color:blue"] 

                        if all(missing) not in removed:
                                newlist.append(removed) #append to new list
                        print(newlist)

如果我想查找两者之间是否存在任何不匹配,这将起作用,我理解为什么它通过all()方法来执行此操作,但我无法找到该方法的良好替代方法。 我尝试过的一切总是返回完整列表,因为它找到了一个不匹配的项目。

如果我尝试对删除的 [s] 执行 while 循环并增加计数,我将得到“需要字符串作为左操作数,而不是布尔值”

还是 Python 新手,所以感谢知识共享。 谢谢!

尝试这个:

missing = [item for item in list2 if f"{item.split(':')[0]}:" not in list1]
print(missing)

输出:

['black', '2']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM