Pythonic 交换? [英] Pythonic Swap?

查看:31
本文介绍了Pythonic 交换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现我必须在 python 中执行交换,我写了这样的东西.

I found that i have to perform a swap in python and i write something like this.

arr[first], arr[second] = arr[second], arr[first]

我想这不是那么 Pythonic.有人知道如何在python中进行更优雅的交换吗?

I suppose this is not so pythonic. Does somebody know how to do a swap in python more elegent?

我想再举一个例子来说明我的疑虑

I think another example will show my doubts

self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[someindexB], self.memberlist[someindexA]

这是在 python 中唯一可用的交换解决方案吗?我确实搜索了很多,但没有找到一个好的答案...

is this the only available solution for swap in python? I did searched a lot but didn't find a nice answer...

推荐答案

我可能会在您的示例代码中更改一件事:如果您打算使用一些长名称,例如 self.memberlist一遍又一遍,首先将其别名(分配")为较短的名称通常更具可读性.因此,例如,而不是冗长的、难以阅读的:

The one thing I might change in your example code: if you're going to use some long name such as self.memberlist over an over again, it's often more readable to alias ("assign") it to a shorter name first. So for example instead of the long, hard-to-read:

self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[someindexB], self.memberlist[someindexA]

你可以编码:

L = self.memberlist
L[someindexA], L[someindexB] = L[someindexB], L[someindexA]

请记住,Python 是按引用工作的,因此 L 指代与 self.memberlist 完全相同的对象,而不是副本(同样,无论列表有多长,赋值都非常快可能是,因为无论如何它都没有被复制——这只是一个参考).

Remember that Python works by-reference so L refers to exactly the same object as self.memberlist, NOT a copy (by the same token, the assignment is extremely fast no matter how long the list may be, because it's not copied anyway -- it's just one more reference).

我认为不需要任何进一步的复杂化,尽管当然可以很容易地想到一些花哨的,例如(对于 a, b 正常"索引 >=0):

I don't think any further complication is warranted, though of course some fancy ones might easily be conceived, such as (for a, b "normal" indices >=0):

def slicer(a, b):
  return slice(a, b+cmp(b,a), b-a), slice(b, a+cmp(a,b), a-b)

back, forth = slicer(someindexA, someindexB)
self.memberlist[back] = self.memberlist[forth]

我认为弄清楚这些高级"用途是一种很好的自负、有益的心理锻炼和很好的乐趣——我建议感兴趣的读者,一旦总体思路清晰,就专注于那些<代码>的作用+cmp 以及它们如何使事情适用于三种可能性 (a>b, a<b, a==b) [[但不适用于负索引 - 为什么不这样做,切片器需要如何改变解决这个问题?]].但是,在生产代码中使用这种奇特的方法通常会矫枉过正,而且毫无根据,与简单直接的方法相比,会使事情变得更加模糊和难以维护.

I think figuring out these kinds of "advanced" uses is a nice conceit, useful mental exercise, and good fun -- I recommend that interested readers, once the general idea is clear, focus on the role of those +cmp and how they make things work for the three possibilities (a>b, a<b, a==b) [[not for negative indices, though -- why not, and how would slicer need to change to fix this?]]. But using such a fancy approach in production code would generally be overkill and quite unwarranted, making things murkier and harder to maintain than the simple and straightforward approach.

记住,简单胜于复杂

这篇关于Pythonic 交换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆