首页 > 解决方案 > 字符串连接/索引给出 IndexError

问题描述

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

我的代码如下:

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 是字符串的长度)等,但没有占上风。有类似问题的消息来源但它们似乎没有帮助。

我究竟做错了什么?

标签: python

解决方案


正如评论中提到的,似乎最有可能的问题是您实际上并没有传递字符串。在对字符串执行拆分之前尝试打印类型(即 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)。


推荐阅读