[英]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?如何制作一个搜索匹配项并将它们放入列表的函数/for循环?
matches = ['dog', 'fish']
You can do set.intersection
if order does not matter:如果顺序无关紧要,您可以执行
set.intersection
:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.