python - 如何使用另一个列表从列表中选择元素?
问题描述
我有两个列表,想显示所有list1
具有共同元素的list2
元素 - 在这种情况下是'a'
:
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'a', 'a', 'c']
预期结果:
[1, 3, 4]
解决方案
这样的事情呢?
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]
推荐阅读
- java - 为什么我的排序算法返回相同数量的比较?
- c++ - 我应该使用 Nuget 或 Vcpkg 安装适用于 C++ 的 AWS 开发工具包吗?
- javascript - 我怎样才能让我的倒计时计时器在我每次用 JavaScript 刷新时停止重新开始
- r - R list.files 未显示所有文件(可能是路径问题?)
- reactjs - 访问 reactjs 结构中的元素
- blockchain - 超级账本和 ICO 代币
- javascript - Twitter API - 发布收藏夹/创建特定速率限制
- html - 通过 ASP 中的类标签而不是通过 ID 标签隐藏/显示 HTML div
- list - Haskell - 根据列表索引重复列表的元素
- java - 在 Intellij IDEA 异常断点条件下调用自定义函数