简体   繁体   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?

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.

相关问题 如何将两个列表中的字符串项融合到新列表的新元素中? - How do you fuse string items from two lists into new elements of a new list? 如何从两个列表创建元组,以便重复一个列表元素 - How do you create Tuples from two lists so that one list elements repeat 如何将列表作为新项目加入列表字典-python? - How do you join a list to a dictionary of lists as a new item - python? 如何匹配两个不同列表中的项目并根据 python 中的匹配项创建新列表? - How to match items in two different lists and create a new list based on the matches in python? 如果包含列表的列包含来自另一个更大列表的元素,你如何 output boolean? - How do you output boolean if column containing lists have elements from another larger list? 在Python中,如何将列表中的第一个元素乘以一个数字(列表中的列表)? - How do you multiply the first element in a list by a number (in a list of lists) in Python? 如何合并两个列表并将它们作为新列表中的元组返回? - How do you merge two lists and return them as a tuple in a new list? Python:如何在python的列表列表中添加列表? - Python: How do you add a list to a list of lists in python? 如何创建两个变量列表? - How do you create a two variable list? 如何在python中创建新线程? - How do you create a new thread in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM