Python:交换两个元素,并将其他特殊字符的位置保留在列表中



源数据

lst = [1, '^', 3, 5, '!', 'a', '%', 'b', '.', 12, '*']

所需结果:

[12, '^', 'b', 'a', '!', 5, '%', 3, '.', 1, '*']

问题:

我想交换两个元素,并将特殊字符的位置保留在列表中。

仅交换1和12、3和b,5和a。(我想提高效率(

同时从左右遍历列表,如果两个元素不是特殊字符,则两个要素将被交换位置?

此方法产生您期望的结果:

import string
lst = [1, '^', 3, 5, '!', 'a', '%', 'b', '.', 12, '*']
# i = Start_Position, j = End_Position
i, j = 0, len(lst)-1
# Traverse while Start_Position < End_Position
while i < j:
   # Swap values at Start_Position and End_Position if not special characters and update indexes
   if str(lst[i]) not in string.punctuation and str(lst[j]) not in string.punctuation:
     lst[i], lst[j] = lst[j], lst[i]
     i += 1
     j -= 1
   # Decrease End_Position as special character found
   elif str(lst[i]) not in string.punctuation and str(lst[j]) in string.punctuation:
     j -= 1
   # Increase Start_Position as special character found
   elif str(lst[i]) in string.punctuation and str(lst[j]) not in string.punctuation:
     i += 1
   # Both values are special characters , update indexes
   else:
     i += 1
     j -= 1
print(lst)
Input : [1, '^', 3, 5, '!', 'a', '%', 'b', '.', 12, '*']
output: [12, '^', 'b', 'a', '!', 5, '%', 3, '.', 1, '*']

这是我的方法。主要想法是交换仅非特殊字符的冠军,然后填充保留特殊字符位置的输出列表。

输入:

lst = [1, '^', 3, 5, '!', 'a', '%', 'b', '.', 12, '*']

找到特殊字符的位置:

import string
spec_pos = [idx for idx, el in enumerate(lst) if str(el) in string.punctuation]

获取非特殊值:

to_swap = [el for idx, el in enumerate(lst) if str(el) not in string.punctuation]

使用递归将通用函数定义为交换列表中的元素:

def rec_swap(l):
    if len(l) == 1:
        return l
    if len(l)==2:
        l[0], l[1] = l[1], l[0]
        return l
    else:
        return [l[-1]] + rec_swap(l[1:-1]) + [l[0]]

交换元素:

swapped = rec_swap(sublist)

创建输出列表:

out = []
_ = [out.append(swapped.pop(0)) if idx not in spec_pos else out.append(lst[idx]) for idx, el in enumerate(lst)]

这给出了预期的输出:

out
Out[60]: [12, '^', 'b', 'a', '!', 5, '%', 3, '.', 1, '*']

相关内容

最新更新