在Python中交换连续的偶数元素
假设我们有一个称为nums的数字列表,我们必须彼此交换每个连续的偶数整数。
因此,如果输入类似于nums=[4、5、6、8、10],则输出将为[6、5、4、10、8]
让我们看下面的实现以更好地理解
示例
class Solution:
def solve(self, nums):
temp = None
for i in range(len(nums)):
if nums[i] % 2 == 0:
if temp is not None:
nums[i], nums[temp] = nums[temp], nums[i]
temp = None
else:
temp = i
return nums
ob = Solution()
print(ob.solve([4, 5, 6, 8, 10]))输入项
[4, 5, 6, 8, 10]
输出结果
[6, 5, 4, 10, 8]
热门推荐
4 祝福语简短的微信
10 对老人新年祝福语简短
11 上班祝福语简短10字
12 朋友买新房祝福语简短
13 离职送别文案祝福语简短
14 生日祝福语宿舍舍友 简短
15 升班祝福语简短10字
16 结婚伴娘祝福语简短精辟
17 对部门师姐祝福语简短
18 旅游祝福语简短老师发言