How to Compare Two Lists in Python and Return Matches

How can I compare two lists in python and return matches

Not the most efficient one, but by far the most obvious way to do it is:

>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
{5}

if order is significant you can do it with list comprehensions like this:

>>> [i for i, j in zip(a, b) if i == j]
[5]

(only works for equal-sized lists, which order-significance implies).

How to compare two lists of strings and return the matches

Try this (quick and dirty):

animals = ["dog", "bear", "monkey", "bird"]
pets = ["dog", "bird", "cat", "snake"]

print("The original list 1 : " + str(animals))
print("The original list 2 : " + str(pets))
res = []
for a in animals:
for p in pets:
if a == p:
res.append(a)


print("The Match indices list is : " + str(res))

How to compare two lists in Python and count ALL matches?

You can use sum instead of any and get the result immediately:

global_fruit = ['apples', 'bananas', 'pears', 'oranges', 'peaches', 'apricots', 'mangoes']
local_fruit = ['bananas', 'apricots', 'oranges']

count = sum(f in global_fruit for f in local_fruit)

print(count)

Also, you could convert your lists into sets and find the number of intersections:

global_fruit = ['apples', 'bananas', 'pears', 'oranges', 'peaches', 'apricots', 'mangoes']
global_fruit_set = set(global_fruit)
local_fruit = ['bananas', 'apricots', 'oranges']
local_fruit_set = set(local_fruit)

count = len(global_fruit_set.intersection(local_fruit_set))
print(count)

python: compare two lists and return matches in order

Convert b to a set and then loop over a's items and check if they exist in that set:

>>> s = set(b)
>>> [x for x in a if x in s]
['a', 'd']

How to compare two lists of strings whose elements patially match

Use zip-function and for-loop:

for a_string, b_string in zip(list_a, list_b):
if a_string[0:21] == b_string[0:21]:
print("a_string anf b_string are partially identical")

How can I compare two lists of lists in Python and find matching values

You are looking for the set intersections of the product of your 'labels', where each pair is itself a set too (order doesn't matter, if 2-4 and 4-2 are considered the same).

Intersections are most efficiently tested with the Python set type, so when building those dictionaries lets convert them to sets up front.

So we need the unique labels, and a way to look up the associated list for each label. That's the job for dictionaries, so convert your lists to dictionaries first, and get the union of their keys. Then turn each pairing into a set as well so {'2', '4'} and {'4', '2'} are seen as the same, storing the results in another set. Note that 2-2 becomes 2 in this scenario, as a set would store '2' just once.

Then all we have to do is test if there is an intersection between the two lists associated with the picked combination of keys, and include that combo if there is:

from itertools import product

dict1 = {k: set(l) for k, l in list1}
dict2 = {k: set(l) for k, l in list2}
keys = dict1.keys() | dict2.keys() # all unique keys in both

found = {
frozenset((k1, k2))
for k1, k2 in product(keys, repeat=2)
if dict1.get(k1, set()) & dict2.get(k2, set())
}

Demo:

>>> from itertools import product
>>> dict1 = {k: set(l) for k, l in list1}
>>> dict2 = {k: set(l) for k, l in list2}
>>> keys = dict1.keys() | dict2.keys() # all unique keys in both
>>> {
... frozenset((k1, k2))
... for k1, k2 in product(keys, repeat=2)
... if dict1.get(k1, set()) & dict2.get(k2, set())
... }
{frozenset({'3', '4'}), frozenset({'2'}), frozenset({'3', '5'}), frozenset({'2', '5'}), frozenset({'2', '3'}), frozenset({'2', '4'}), frozenset({'1', '3'})}

If you must have doubled-up references, you can post-process the result:

for combo in found:
try:
a, b = combo
except ValueError: # doesn't contain 2 values, assume 1
a, = b, = combo
print(f'{a}-{b}')

The order will vary dependant on the current random hash seed, so you may want to use sorting. I get this output:

3-4
2-2
3-5
2-5
2-3
2-4
1-3

How to compare two lists and decide one matches the other?

Here is an efficient solution. For each element in the second list, get the next element of the first one until you have a match. If you reach the end of the first list before you matched all, this is False else True

def check(a, b):
i = iter(a)
return all(e in i for e in b)

Or manual version:

def check(a, b):
i = iter(a)
for e in b:
try:
while e != next(i):
pass
except StopIteration:
return False
return True

Test:

for l in [l2, l3, l4, l5, l6]:
print(check(l1, l))

Output:

False
True
True
False
False

How can I compare two lists in python and return not matches

Just use a list comprehension:

def returnNotMatches(a, b):
return [[x for x in a if x not in b], [x for x in b if x not in a]]

How to compare strings in two lists and create a third of the matches?

I made the correct guesses list using a list comprehension:

correct_guess_list = ["O " if random_food_list[player_guess_list.index(food)] == food else "X" for food in
player_guess_list]

Full code:

import random


def start_game():
food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
random_food_list = random.choices(food_list, k=4)
player_guess_list = []
correct_guess_list = []
correct_guesses = 0

for i in range(1, 5):
player_guess = input("food" + str(i) + ":").lower()
if player_guess not in food_list:
print("Invalid foods, Restart Again")
start_game()
else:
player_guess_list.append(player_guess)
if player_guess_list[i-1] == random_food_list[i-1]:
correct_guesses += 1
print(player_guess_list) # For review
print(random_food_list) # For review
correct_guess_list = ["O " if random_food_list[player_guess_list.index(food)] == food else "X" for food in
player_guess_list]
print(correct_guess_list)
print(f"Food in correct place: {correct_guesses}")
print(f"Food in incorrect place: {4 - correct_guesses}")


start_game()


Related Topics



Leave a reply



Submit