簡體   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