[英]Python: swap two elements and keep the position of other special characters in a list?
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, '*']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.