I'm working on a script that compares two lists and outputs if one or more are missing a term from list1
. The end goal is to search all of list1
against list2[0]
, then list2[1]
etc. If there is no match, append to a new list to be printed out later.
list1
is the search, multiple values and static list2
is the values to search against, could be 1 to 50 values depending on input I'm grabbing from a file that I have parsed.
list1 = ["color:", "size:", "tip:"]
list2 = ["color:red", "color:purple", "black", "size:2", "tip:small", "tip:large", "size:4", "2", "color:blue"]
Here we see black and 2 are missing a parameter from list1
. The idea would be ["black", "2"]
are appended to a new variable to be called on later as "missing parameter". If items from list1
do not exist, the search the user is doing via list2
will not work.
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)
This would work if I was looking to find if there are any non-match between the two, I understand why it's doing it via the all()
method but I'm not able to find a good alternative to the approach. Everything I have tried always returns the full list because it finds one item that doesn't match.
If I try doing a while loop against removed[s] and up the count, I will get "requires string as left operand, not bool"
Still new to Python so appreciate the knowledge sharing. Thanks!
Try this:
missing = [item for item in list2 if f"{item.split(':')[0]}:" not in list1]
print(missing)
Output:
['black', '2']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.