python - 如何搜索项目集合是否在列表中?

标签 python python-3.x bioinformatics

我正在迭代一个文件,并试图确定是否在我创建的空列表中找到了一组特定的 3 个项目(来自文件);如果没有,我想附上它们。如果它们已经出现,我想跳过它们。

但是,当我运行以下代码时:

from pprint import pprint as pp

targets = open(file)

longest_UTR = []

counter = 0

for line in targets:

    (chromosome, locus, mir, gene, transcript, UTR_length) = line.strip("\n").split("\t")

    if [locus, mir, gene] not in longest_UTR:

        longest_UTR.append([locus, mir, gene, transcript, UTR_length])

    counter += 1

    if counter == 100:

        break

pp (longest_UTR)

我发现输出包含重复项,即它没有跳过该组项目,即使它们出现在空列表中(如下面的箭头所示)。

['CFI', 'hsa-miR-576-5p', 'DIS3', 'ENST00000490646', '2934'],
['APOE', 'hsa-miR-642a-5p', 'WDR64', 'ENST00000425826', '2122'],
>['C2/CFB/SKIV2L', 'hsa-miR-219a-1-3p', 'GLG1', 'ENST00000422840', '4748'],
['C2/CFB/SKIV2L', 'hsa-miR-219a-1-3p', 'GLG1', 'ENST00000422840', '4748']<,
['APOE', 'hsa-miR-330-3p', 'DCAF4L1', 'ENST00000333141', '4764'],
['TMEM97/VTN', 'hsa-miR-144-3p', 'DCAF4L1', 'ENST00000333141', '4764']]

我想要一些关于为什么会出现这种情况的指导。谢谢。

最佳答案

列表不可散列,因此不能按照您想象的方式比较两者之间的相等性。列表比较可以使用sets来完成反而。

从 pprint 导入 pprint 作为 pp

targets = open(file)

longest_UTR = []

for line in targets:
    chromosome, locus, mir, gene, transcript, UTR_length = line.strip("\n").split("\t")

    if not [set([locus, mir, gene]) < set(utr) for utr in longest_UTR]:
        longest_UTR.append([locus, mir, gene, transcript, UTR_length)])
pp (longest_UTR)

关于python - 如何搜索项目集合是否在列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53101449/

相关文章:

python - 为什么 `str.format()` 会忽略其他/未使用的参数?

python - pandas.apply 期望输出形状(传递值的形状是(x,),索引暗示(x,y))

python - 从 SRE_Match 对象获取跨度和匹配值 (Python)

python - Visual Studio,OpenCV,Python-应用中无网络摄像头

Python:将并行数组 reshape 为训练集

python - 如何在图表区的 Python-pptx 图表中为图表提供图表标题(不是幻灯片标题)

string - 根据常见的子模式对短的、同质的字符串 (DNA) 进行聚类并提取类的共识

python - 如何使线图中的颜色在 matplotlib 和 python 中淡出

python - 在 python 中重新定义 Netcdf 文件

python - 为字符的矩形矩阵添加边框(*)