Python中交换2个数组元素的位置
有没有简单的方法可以交换数组中 2 个元素(或者更好的是 n 个元素)的位置?
我想出了一些代码,但它看起来很丑陋,而且性能应该有点差:
chromo = [[1,2], [3,4], [5,6]]
gene1Pos = random.randrange(0, len(chromo)-1, 1)
gene2Pos = random.randrange(0, len(chromo)-1, 1)
tmpGene1 = chromo[gene1Pos]
tmpGene2 = chromo[gene2Pos]
chromo[gene1Pos] = tmpGene2
chromo[gene2Pos] = tmpGene1
这应该可行,但是,这并不好。更好的方法是像 random.shuffle 这样的例程,但不是混合所有内容,而是只混合 n 个元素。你有什么想法吗?
Is there any easy way to exchange the position of 2 elements - or better yet, n elements - in an array?
I came up with some code, but it looks quite ugly and the performance should be a bit bad:
chromo = [[1,2], [3,4], [5,6]]
gene1Pos = random.randrange(0, len(chromo)-1, 1)
gene2Pos = random.randrange(0, len(chromo)-1, 1)
tmpGene1 = chromo[gene1Pos]
tmpGene2 = chromo[gene2Pos]
chromo[gene1Pos] = tmpGene2
chromo[gene2Pos] = tmpGene1
This should work, but well, it's not nice. The better way would be a routine like random.shuffle but that instead of mixing everything would mix just a number n of elements. Do you have any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
所以你只需要确保你有正确的 genXPos
try
So you just need to make sure you have the right genXPos
只需将 Python 中交换变量的正常机制与切片/切片赋值结合起来即可。
Just combine the normal mechanism for swapping variables in Python with slicing/slice assignment.
你所做的事情没有任何问题。不过,您可以通过删除临时变量之一来简化它。要交换
a
和b
,您所需要做的就是:There's nothing wrong with what you're doing. You can simplify it by removing one of the temp variables though. To swap
a
andb
, all you need is this: