内部字符串数组交换

时间:2018-12-28 02:35:10

标签: arrays python-3.x string

我尝试将内部字符串数组值与其他数组,堆栈等交换。
示例:

s = [1,2,3,4,5,6,7,8]
output= [1,5,2,6,3,7,4,8]

我的解决方案如下所示,但我认为这不是最佳解决方案。有人可以纠正我的代码效率吗?

[python3]
class Solution:
    def inner_number(self, s):
        i=len(s)//2
        index=1
        while i < len(s):
            for j in range(i,index,-1):
                s[j-1],s[j]=s[j],s[j-1]
            i+=1
            index+=2
        return s

2 个答案:

答案 0 :(得分:0)

[ { "id": "f98nu4505fd782" "firstname": "John", "lastname": "Doe", "departments": [ { "id": "d8nn83873434", "name": "Department 1 Name" }, { "id": "9d8n892030e9", "name": "Department 2 Name" } ] } ]

答案 1 :(得分:0)

s = [1,2,3,4,5,6,7,8,9] 
h = len(s)//2
res= []
if len(s)%2==1:
    res = [j for i in zip(s[:h],s[h:]) for j in i] + [s[-1]]
else:
    res = [j for i in zip(s[:h],s[h:]) for j in i]
print(res)
# output [1, 5, 2, 6, 3, 7, 4, 8, 9]