繁体   English   中英

在 Python 中,如果您有两个共享多个元素的列表,您如何创建具有匹配项的新列表?

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

如果您有两个共享多个元素的列表,您如何找到匹配项并创建这些元素的新列表?

前任。)

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

如何制作一个搜索匹配项并将它们放入列表的函数/for循环?

 matches = ['dog', 'fish']

如果顺序无关紧要,您可以执行set.intersection

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

或者,如果顺序很重要,您可以进行列表理解:

[x for x in first if x in second]

尝试这个:

 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.

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