【问题标题】:String concatenation/indexing giving IndexError字符串连接/索引给出 IndexError
【发布时间】:2018-06-26 08:17:19
【问题描述】:

我正在尝试一些相对基本的字符串连接,但似乎无法找到我收到的错误的来源。

我的代码如下:

def crossover(dna1, dna2):
    """
    Slices both dna1 and dna2 into two parts at a random index within their
    length and merges them.
    """
    pos = int(random.random()*DNA_SIZE)
    return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:])

后来,我通过以下方式引用这个函数,其中变量ind1Affind2Aff之前已经定义为二进制字符串

ind1Aff, ind2Aff = crossover(ind1Aff, ind2Aff)

但是,在运行我的代码时,我收到以下错误

    return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:])
IndexError: invalid index to scalar variable.

我尝试将其稍微更改为dna1[0:pos]+dna2[pos:DNA_SIZE](其中 DNA_SIZE 是字符串的长度)等,但没有占上风。有同样问题的来源,如 this,但它们似乎没有帮助。

我做错了什么?

【问题讨论】:

  • ... 你确定那些是字符串吗?在使用内置类型时,我从未见过该错误。
  • 尝试一些dna1dna2 的样本值。它们当然不是字符串。
  • 代替 ind1Aff 和 ind2Aff 传递的值是什么?
  • 使用的值是二进制字符串,所以其中一个值类似于1010001100001000
  • 你能检查你的二进制字符串的type 吗?你确定它是一个字符串而不是其他一些自定义数据结构吗?

标签: python


【解决方案1】:

正如 cmets 中提到的,最有可能的问题是您实际上并未传递字符串。在对字符串执行拆分之前尝试打印类型(即 type(dna1))。

当你传递一个普通的 python 字符串时,你的代码会按预期工作:

import random


def crossover(dna1, dna2):
    """ 
    Slices both dna1 and dna2 into two parts at a random index within their
    length and merges them.
    """
    DNA_SIZE = len(dna1)
    pos = int(random.random()*DNA_SIZE)
    return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:])


def main():
    one = '000000000000000'
    two = '111111111111111'
    ind1Aff, ind2Aff = crossover(one, two)
    print ind1Aff
    print ind2Aff


if __name__ == "__main__":
    main()

输出:

000011111111111
111100000000000

您还可以在应用字符串拆分之前输入 str(dna1) 和 str(dna2)。

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    相关资源
    最近更新 更多