在列表中反向随机选择的时间间隔-python 3

问题描述 投票:0回答:2

请考虑以下示例:

x = [ 8, 1 , 3 , 6 , 2 , 10 , 18, 4, 7 ]

n1 = randrange( len(x) )  
n2 = randrange( len(x) )  

while abs( n1 - n2 ) <= 2 :      # to make sure that they are at least two elements
    n1 = randrange( len(x) )
    n2 = randrange( len(x) )

---> n1 , n2 = 2 , 5              

我想还原两个随机选择的位置n1,n2之间的部分x [n1 + 1,n2] = [6,2]。

正确的方法应产生以下结果(在n1 = 2,n2 = 5的情况下)

 x = [ 8, 1 , 3 , **2** , **6** , 10 , 18, 4, 7 ]

我自己解决了这个问题,但结果很“丑陋”,我正在寻找更好的方法

x = [ 8, 1 , 3 , 6 , 2 , 10 , 18, 4, 7 ]

n1 = randrange( len(x) )
n2 = randrange( len(x) )

empty = []

while abs( n1 - n2 ) <= 2 :

    n1 = randrange( 10 )
    n2 = randrange( 10 )

    # sort n1, n2
    empty.append( n1 ) , empty.append( n2 )  
    empty = sort(empty)
    n1 , n2 = empty[0] , empty[1]

    # reverse the randomly chosen part
x_new = x[ n1 + 1 : n2 ]
x[ n1 + 1 : n2 ] = x_new[ :: -1 ]
python list reverse
2个回答
0
投票

您可以这样操作:

from random import randint

x = [8, 1, 3, 6, 2, 10, 18, 4, 7]

n1 = randint(0, len(x)-4)
n2 = randint(n1 + 3, len(x)-1)

res = x[:n1+1] + x[n1+1:n2][::-1] + x[n2:]

对我来说看起来更优雅。

示例运行:

n1 = 3, n2 = 7, res:    [8, 1, 3, 6, 18, 10, 2, 4, 7]
n1 = 5, n2 = 8, res:    [8, 1, 3, 6, 2, 10, 4, 18, 7]
n1 = 2, n2 = 6, res:    [8, 1, 3, 10, 2, 6, 18, 4, 7]
n1 = 3, n2 = 8, res:    [8, 1, 3, 6, 4, 18, 10, 2, 7]
n1 = 1, n2 = 5, res:    [8, 1, 2, 6, 3, 10, 18, 4, 7]
n1 = 0, n2 = 5, res:    [8, 2, 6, 3, 1, 10, 18, 4, 7]
n1 = 3, n2 = 6, res:    [8, 1, 3, 6, 10, 2, 18, 4, 7]
n1 = 4, n2 = 8, res:    [8, 1, 3, 6, 2, 4, 18, 10, 7]
n1 = 0, n2 = 8, res:    [8, 4, 18, 10, 2, 6, 3, 1, 7]

这里的主要目的是指定randint的范围,以避免while循环。您对n1n2的要求非常简单。优点是您不必担心顺序或范围长度。


0
投票
from random import *
x = [ 8, 1 , 3 , 6 , 2 , 10 , 18, 4, 7 ]

n1 = randrange( len(x) )  
n2 = randrange( len(x) )  
n1,n2 = 2,5 ## remove this line after testing
tmp = []
if (n2>n1):
    tmp += x[:n1+1]
    tmp += x[n2-1:n1:-1]
    tmp += x[n2:]
elif (n2<n1):
    tmp += x[:n2+1]
    tmp += x[n1-1:n2:-1]
    tmp += x[n1:]
else:
    tmp = x
print(tmp)
© www.soinside.com 2019 - 2024. All rights reserved.