【问题标题】:Python: How to define string indices as variablesPython:如何将字符串索引定义为变量
【发布时间】:2019-07-22 14:34:42
【问题描述】:

(经过多年的 R 使用,刚接触 Python)

假设我有一个字符串:

dna = "gctacccgtaatacgtttttttttt"

我想预先定义感兴趣的索引:

window_1 = 0:3
window_2 = 1:4
window_3 = 2:5

这是无效的 Python 语法。所以我尝试了:

window_1 = range(0, 3)

当我尝试使用 window_1 变量作为字符串索引时,这不起作用:

dna[window_1]

但我收到"string indices must be integers" 错误。

我尝试了很多方法,例如将 range() 包装在 int() 和/或 list() 中,但没有任何效果。

谢谢

【问题讨论】:

标签: string integer indices


【解决方案1】:

当您设置变量window_1、window_2 和window_3 时,首先您必须告诉它您希望它查看的位置来抓取您告诉它抓取的这些索引,因此您需要告诉它查看你的变量'dna'。其次,索引应该放在方括号中。还要记住,Python 使用从零开始的编号系统。因此,就 Python 而言,您的 dna 序列 (g) 中的第一个位置是零位置。第二个位置(c)实际上是第一个位置。

dna = "gctacccgtaatacgtttttttttt"

window_1 = dna[0:3] window_2 = dna[1:4] window_3 = dna[2:5]

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 2019-07-09
    • 2019-11-24
    • 1970-01-01
    相关资源
    最近更新 更多