![](/img/trans.png)
[英]how to generate list of lists from conditional items in another list of lists
[英]Python: How to generate list with items repeating in two lists
我有兩個項目清單:
list_1 = ['A', 'B', 'C', 'C', 'D']
list_2 = ['C', 'C', 'F', 'A', 'G', 'D', 'C']
我想用兩個列表中的元素創建一個新列表。 像這樣:
['A', 'C', 'C', 'D']
請注意,應該記住,任何項目都可以在列表中重復多次,並且在新列表中出現的次數應該與在兩個列表中重復的次數一樣多。 例如,“C”在 list_1 中重復了 2 次,在 list_2 中重復了 3 次,因此它在結果中出現了 2 次。
經典的方法是:
import copy
result = []
list_2 = fruit_list_2.copy()
for fruit in fruit_list_1:
if fruit in list_2:
result.append(fruit)
list_2.remove(fruit)
但我有興趣通過生成列表來做到這一點:[number for number in numbers if number > 0]。 可能嗎?
如果您不太關心新列表的順序,可以使用collections.Counter
。
>>> list((Counter(list_1) & Counter(list_2)).elements())
['A', 'C', 'C', 'D']
&
將兩者的交集作為多集,最小計數用於公共元素。 elements
方法將結果中的項目作為迭代器返回,因此是list
包裝器。
from collections import Counter
list_3 = list((Counter(list_1) & Counter(list_2)).elements())
我認為這很簡單:
list_1 = ['A', 'B', 'C', 'C', 'D']
list_2 = ['C', 'C', 'F', 'A', 'G', 'D', 'C']
list_3 = [x for x in list_1 if x in list_2]
print(list_3)
# returns ['A', 'C', 'C', 'D']
嘗試這個:
[common for common in list_1 if common in list_2]
學習愉快...:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.