简体   繁体   中英

How to compare two lists of strings and return the matches

I have this question as homework and I can't figure it out.

You have 2 lists of strings with contents of your choice. Use a loop that goes through the lists and compares the lists elements and displays only the list elements that duplicate (the element exists in both lists). The strings should be displayed even if in one is used uppercase and in the other lowercase or a combination of it.

I don't know why it's not working.

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 = [animals.index(i) for i in pets]

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

Maybe this is what you were searching for.

l1 = ["asd", "dfs", "anv"]
l2 = ["asds", "dfs", "anv"]
temp = [x for x in l1 if x in l2]
print(temp)

If statements are to be used when comparing between two strings.

It's better to check for dictionary or set membership, than using list.index.

Dictionary lookup is a O(1) operation, compared to list.index or x in list ( list.__contains__ ) which is O(n).

You can construct a dictionary where the names map to the index in the input list.

>>> animals = ["dog", "bear", "monkey", "bird"]
>>> pets = ["dog", "bird", "cat", "snake"]
>>> animals_mapping = {name.lower(): idx for idx, name in enumerate(animals)}
>>> animals_mapping
{'dog': 0, 'bear': 1, 'monkey': 2, 'bird': 3}

>>> [animals_mapping.get(name.lower(), -1) for name in pets]
[0, 3, -1, -1]

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))

I updated your code a bit so that it caters to similar elements with different casings (uppercase/lowercase)

animals = ["dOg", "bear", "monkey", "bIrd"]
pets = ["doG", "Bird", "cat", "snake"]

for x in range(len(pets)):
    pets[x] = pets[x].lower()

match = [x.lower() for x in animals if x.lower() in pets]
print("The original list 1 : " + str(animals))
print("The original list 2 : " + str(pets))
print("matched element(s) in both lists: ", match)

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.

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