python - 为什么 Python 无法识别集合中的元素?

标签 python

我正在尝试从一组字符串中删除元素,但未找到它们。 该集生成为卡住集(由超出问题范围的库生成),我将其转换为常规集。

>>> geneset = model.reactions[2915].genes
>>> geneset
frozenset(['YGL080W', 'YGR243W', 'YHR162W', 'AND', 'OR'])
>>> geneset_mutable = set(geneset)
>>> geneset_mutable
set(['YGR243W', 'OR', 'YGL080W', 'AND', 'YHR162W'])
>>> 'OR' in geneset_mutable
False
>>> "OR" in geneset_mutable
False
>>> geneset_mutable.remove('OR')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'OR'

集合是可编辑的:

>>> geneset_mutable.add('OR')
>>> "OR" in geneset_mutable
True
>>> geneset_mutable.remove('OR')
>>> "OR" in geneset_mutable
False
>>> geneset_mutable
set(['YGR243W', 'AND', 'YHR162W', 'OR', 'YGL080W'])
>>> geneset_mutable.remove('OR')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'OR'

为什么找不到元素? 有什么特别的方法可以对此进行调试吗?

备案:

>>> sys.getdefaultencoding()
python -V
Python 2.7.5

最佳答案

如果你直接输入集合,它工作正常:

geneset_mutable = set(['YGR243W', 'OR', 'YGL080W', 'AND', 'YHR162W'])
>>> "OR" in geneset_mutable
True

我得出的结论是 model.reactions[2915].genes 没有返回字符串,它返回的基因的 repr 看起来像“OR”但是是不同类型的对象(与您的查询不匹配的一个)。

这很容易确认,只需运行这样的测试:

for gene in geneset:
    if repr(gene) == 'OR':
       print repr(gene)
       print type(gene)
       print gene == 'OR'

解决方案是创建一个可以与集合成员完全匹配的基因对象。你如何做到这一点取决于你的模型是如何实现的,但它应该看起来像这样:

>>> geneset = model.reactions[2915].genes
>>> Gene('OR') in geneset
True

希望这能让您回到完成基因分析的道路上:-)

关于python - 为什么 Python 无法识别集合中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23850363/

相关文章:

python - 函数中的继承在 Python 中是可能的吗?

python - Scipy.Odr 多变量回归

python - Matplotlib 填充缺失的 Tic 标签

python - numpy array - 使用 np.concatenate 或 np.insert 将零行添加到 ndarray

python - 获取一个标签外和另一个标签内的文本

python - Bootstrap 导航菜单下拉菜单不起作用

python - 如何在 Elasticsearch python 中组合这两个查询?

python - 最大 Twitter ID?

python - 从两个稀疏矩阵计算任意行的点积的快速方法是什么

python - Nexus pypi 存储库 "Could not find a version that satisfies the requirement"