关于Python 2.7.12(免责声明:我理解Python2正在逐步淘汰到Python3,但是我在这里开始的课程,也许是为了理解旧的代码库):
我有一个整数列表,我想用它们的相邻值交换每个整数.到目前为止,这对于包含它们包含的整数数量的列表非常有用,但是当列表长度为奇数时,简单地交换每个值并不容易,因为整数的数量不均匀.
给出以下代码示例,如何交换列表中最终值以外的所有值?
arr = [1, 2, 3, 4, 5]
def swapListPairs(arr):
for idx, val in enumerate(arr):
if len(arr) % 2 == 0:
arr[idx], arr[val] = arr[val], arr[idx] # traditional swap using evaluation order
else:
arr[0], arr[1] = arr[1], arr[0] # this line is not the solution but where I know I need some conditions to swap all list values other than len(arr)-1, but am not sure how to do this?
return arr
print swapListPairs(arr)
Run Code Online (Sandbox Code Playgroud)
奖励指向最终的Pythonic Master:如何修改此代码以交换字符串?现在,我只能使用整数使用这个函数,我很好奇我如何才能使这个int
和str
对象一起工作?
非常感谢您的任何见解或建议,指出我正确的方向!在这里,每个人的帮助都非常宝贵,我感谢您的阅读和帮助!
这是基于切片分配的更短,可能更快的方法:
def swap_adjacent_elements(l):
end = len(l) - len(l) % 2
l[:end:2], l[1:end:2] = l[1:end:2], l[:end:2]
Run Code Online (Sandbox Code Playgroud)
切片赋值选择l
所有偶数索引(l[:end:2]
)或所有奇数索引(l[1:end:2]
)的元素,直到和排除索引end
,然后使用您已经用于交换切片的相同类型的交换技术.
end = len(l) - len(l) % 2
选择要停止的索引.我们设置end
为最小的偶数小于或等于len(l)
减去len(l) % 2
,余数len(l)
除以2.
或者,我们可以end = len(l) & ~1
使用按位运算完成.这将构造一个整数用作mask(~1
),其中1位为0,其他位置为1,然后应用掩码(with &
)将1位设置len(l)
为0以生成end
.
归档时间: |
|
查看次数: |
264 次 |
最近记录: |