python - 字符串连接/索引给出 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:])
后来,我通过以下方式引用了这个函数,其中变量ind1Aff
和ind2Aff
之前已经定义为二进制字符串:
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 是字符串的长度)等,但没有占上风。有类似问题的消息来源,但它们似乎没有帮助。
我究竟做错了什么?
解决方案
正如评论中提到的,似乎最有可能的问题是您实际上并没有传递字符串。在对字符串执行拆分之前尝试打印类型(即 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)。
推荐阅读
- flask - 使用 GStreamer 的 Flask Live HLS 流式处理仅适用于本地计算机
- powerbi - 如何将日期表(日期类型列)连接到事实表日期(日期时间类型列)类型?
- python - Python:在另一个函数中定义一个函数
- r - 根据条件更改列的值(缺失数据和分类)
- java - 如何将两个全局变量添加到 groovy 文件中?
- r - 在 R 中按下一个带有 RSelenium 的按钮。Web 抓取 Google Play
- java - 当运行带有 -jar 选项的 java 命令时,是否可以使用 -cp 提供其他库?
- python - 类型错误:tick_params() 缺少 1 个必需的位置参数:'self'
- sql - 在 SQL Server 中使用插入语句优化必要的 while 循环
- prolog - 使用谓词解决序言中的 kakuro