简体   繁体   中英

In Python, if you have two lists that share a number of elements, how do you create a new list with the matches?

If you have two lists that share a number of elements, how do you find the matches, and create a new list of these elements?

Ex.)

 first = ['cat','dog','parrot','fish']
 second = ['fish', 'hamster', 'mouse', 'dog']

how would make a function/for-loop that searches for the matches and puts them into a list?

 matches = ['dog', 'fish']

You can do set.intersection if order does not matter:

list(set(first).intersection(second))

Or if order matters, you can do a list comprehension:

[x for x in first if x in second]

Try this:

 match = [] for i in first: for j in second: if i == j: match.append(i) print('Match: {}'.format(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