![](/img/trans.png)
[英]How do you fuse string items from two lists into new elements of a new list?
[英]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.