python - Python 中的交叉列表理解

标签 python list-comprehension

假设我有两个字符串列表:

a = ['####/boo', '####/baa', '####/bee', '####/bii', '####/buu']

其中####代表4位随机数。和

b = ['boo', 'aaa', 'bii']

我需要知道列表 a 中的哪个字符串条目包含 b 中的任何给定条目。我能够通过几个嵌套循环然后使用 in 运算符来检查字符串是否包含 b 中的当前条目来完成此操作。但是,作为 py 的新手,我几乎可以肯定这不是最 pythonic 或最优雅的编写方式。那么,有没有这样的成语来减少我的解决方案呢?

最佳答案

以下代码为您提供了一个索引为 a 的数组,其中斜线后的部分是 b 中的元素。

a_sep = [x.split('/')[1] for x in a]
idxs = [i for i, x in enumerate(a_sep) if x in b]

要提高性能,请将 b 设为集合而不是列表。

演示:

>>> a = ['####/boo', '####/baa', '####/bee', '####/bii', '####/buu']
>>> b = ['boo', 'aaa', 'bii']
>>> a_sep = [x.split('/')[1] for x in a]
>>> idxs = [i for i, x in enumerate(a_sep) if x in b]
>>> idxs
[0, 3]
>>> [a[i] for i in idxs]
['####/boo', '####/bii']

如果您更喜欢直接获取元素而不是索引:

>>> a = ['####/boo', '####/baa', '####/bee', '####/bii', '####/buu']
>>> b = ['boo', 'aaa', 'bii']
>>> [x for x in a if x.split('/')[1] in b]
['####/boo', '####/bii']

关于python - Python 中的交叉列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10488684/

相关文章:

python - multiprocessing.Pool 进程锁定到单个核心

python - 将映射 lambda 转换为列表理解

python - 用理解替换 Python 嵌套的 For 循环

python - PySpark 一次替换多个列中的值

python - sqlalchemy.exc.ProgrammingError : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version

python - 在 Jupyter/pandas 中显示 2 位小数,并使用逗号分隔千位?

python - 你如何在不安装软件包的情况下返回 `pip freeze`?

python - 下面的代码有更快的实现吗?

python - "list comprehension"和类似的意思是什么?它是如何工作的,我该如何使用它?

python - 如何在综合嵌套列表中向文本文件添加换行符?