如何随时交换列表中的项目? [英] How to swap items in the list at any point?
本文介绍了如何随时交换列表中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
l = [ 1 ,2 ,3, 4,
5 ,6 , 7,8,
9,10,11,12,
13,14,15,16,
17,18,19,20,
21,22,23,24
]
与下一行交换时在中间进行. 预期的输出:
When swapping with next line is done at the middle. Intended Output:
l = [ 1 ,2 ,7,8,
5 ,6 ,3,4,
9,10,15,16,
13,14,11,12,
17,18,23,24,
21,22,19,20
]
工作代码:
n = len(l) #length of list
c = 4 # column length
h =int(c/2) #middle crossover point
for i in range(int(c/2) , n+1, int(2*c) ):
l[i:i+h], l[i+c:i+(c+h)] = l[i+c:i+(c+h)],l[i:i+h]
print (l)
现在,我的代码仅在交叉点位于中间时才有效.我想将其缩放到任何交叉点.我怎么做 ?对于前.如果交叉点是2nd element,则输出应为:
Now my code works only when crossover point is middle. I want to scale it to any crossover point . How do I do that ? For ex. if the crossover point is 2nd element , output should be:
l = [ 1 ,6,7,8,
5 ,2,3,4,
9,14,15,16,
13,10,11,12,
17,22,23,24,
21,18,19,20
]
还请注意,列的长度可以是任何长度,在此示例中为4.
Also note that the length of column can be anything , in this example it is 4.
推荐答案
在此处使用嵌入式交换.不对所有条件进行测试.
Use in-line swap here. No test for all conditions.
def swap(lst, offset, distance, items):
for i in range(offset, len(lst)-distance-items+1, 2*distance):
lst[i:i+items], lst[i+distance:i+distance+items] = (
lst[i+distance:i+distance+items], lst[i:i+items])
lst = [i+1 for i in range(24)]
swap(lst, 1, 6, 5) # column offset:1, row length:6, item:5 to swap in-line
[ 1, 8, 9, 10, 11, 12,
-------swap--------
7, 2, 3, 4, 5, 6,
13, 20, 21, 22, 23, 24,
-------swap--------
19, 14, 15, 16, 17, 18]
: Parameters
lst - list to swap elements
offset - the start index of elements to swap
distance - the distance between each start index of elements to swap, you can think it is same as width of total columns.
items - the number of continue elements to swap
: Return
None, in-line swap
这篇关于如何随时交换列表中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文