首页 > 解决方案 > 如何使用另一个列表从列表中选择元素?

问题描述

我有两个列表,想显示所有list1具有共同元素的list2元素 - 在这种情况下是'a'

list1 = [1, 2, 3, 4, 5] 
list2 = ['a', 'b', 'a', 'a', 'c']

预期结果:

[1, 3, 4]

标签: pythonlist

解决方案


这样的事情呢?

from collections import Counter
list1= [1,2,3,4,5] 
list2 = ['a','b','a','a','c']
count = Counter(list2)
most_common_char = count.most_common()[0][0]
print([list1[idx] for idx in range(len(list2)) if list2[idx] == most_common_char])
# Prints [1, 3, 4]

推荐阅读